如何从数据库中获取逗号分隔的值 [英] How to get comma separated values from database
问题描述
我有以下mysqli查询,我想让输出的数组变成(1,2,3,4)
类型格式.
I have the following mysqli query, and I want to implode the array that's outputted into a (1,2,3,4)
type format.
这是查询和asoc数组代码:
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 )
)
很抱歉,如果我在这里确实遗漏了一些明显的内容.我一直在尝试修复此问题,由于缺乏PHP经验,我不确定100%确定要搜索什么.
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.
我还尝试使用 $ user_categories
查询的结果进行一次简单的内爆,按照我在该主题上看到的其他StackExchange答案的说明进行操作,但一无所获(以下代码):
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;
推荐答案
$ category_ids
是一个数组数组(行),因此您不能只对其进行内爆.您需要从每一行获取第一个值并将其内爆.
$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.
使用 array_column()
:
$category_ids = implode(', ', array_column($category_ids, 0));
echo $category_ids;
输出:
5、8、4、2
5, 8, 4, 2
PHP 5.3+解决方案:
用 array_map()
代替 array_column()
:
$category_ids = implode(', ', array_map(function ($row) { return $row[0]; }, $category_ids));
echo $category_ids;
输出:
5、8、4、2
5, 8, 4, 2
这篇关于如何从数据库中获取逗号分隔的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!