duanbei1903 2016-07-10 14:16
浏览 413
已采纳

如何从数据库中获取逗号分隔值

I have the following mysqli query, and I want to implode the array that's outputted into a (1,2,3,4) type format.

Here's the query and the asoc array code:

$user_categories = mysqli_query($connect, "SELECT sub_cat FROM subscriptions WHERE sub_user_id = '$user_id'");

$category_ids = mysqli_fetch_all($user_categories,MYSQLI_NUM);

print_r($category_ids);

$category_ids = implode(", ",$category_ids);

I then get the following output, and I can't seem to isolate the values...

Array ( 
[0] => Array ( [0] => 5 ) 
[1] => Array ( [0] => 8 ) 
[2] => Array ( [0] => 4 ) 
[3] => Array ( [0] => 2 ) 
)

Apologies if I'm missing something really obvious here. I've been trying to fix this for a while, and due to my lack of PHP experience, I'm not 100% sure what to search for.

I've also tried a simple implode using the results of the $user_categories query, following the instructions of other StackExchange answers I've seen on the topic, but got nothing (code below):

$user_categories = mysqli_query($connect, "SELECT sub_cat FROM subscriptions WHERE sub_user_id = '$user_id'");

$category_ids = implode(", ",$user_categories);

echo $category_ids;
  • 写回答

3条回答 默认 最新

  • dstobkpm908182 2016-07-10 14:26
    关注

    $category_ids is an array of arrays (rows), so you can't just implode it. You need to fetch the first value from each row and implode that.

    PHP 5.5+ solution:

    Using array_column():

    $category_ids = implode(', ', array_column($category_ids, 0));
    
    echo $category_ids;
    

    Output:

    5, 8, 4, 2

    PHP 5.3+ solution:

    Subtitute array_map() for array_column():

    $category_ids = implode(', ', array_map(function ($row) { return $row[0]; }, $category_ids));
    
    echo $category_ids;
    

    Output:

    5, 8, 4, 2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了