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条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)