How to get comma separated values from database

与世无争的帅哥 提交于 2021-02-04 21:06:34

问题


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;

回答1:


$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:


$category_ids that you get from mysqli_fetch_all is array of arrays and the desired result cannot be retrieved just by passing it to implode. However, this should do the job:

$category_ids = mysqli_fetch_all($user_categories,MYSQLI_NUM);

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

Alternatively, in case you're using PHP 5.5 or higher, you can make it a bit less messy by using array_column:

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



回答3:


Mysql solution

$sql = "SELECT group_concat(sub_cat) FROM subscriptions WHERE sub_user_id = '$user_id'"
$result = mysqli_query($connect, $sql);
$category_ids = mysqli_fetch_row($user_categories)[0];

PDO solution (preferred)

$sql = "SELECT group_concat(sub_cat) FROM subscriptions WHERE sub_user_id = ?"
$stmt = $connect->prepare($sql);
$stmt->execute([$user_id]);
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
$category_ids = implode(",", $array);


来源:https://stackoverflow.com/questions/38292833/how-to-get-comma-separated-values-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!