php 将数组从 mysql 查询中内爆为逗号分隔的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11599917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:50:35  来源:igfitidea点击:

implode an array into a comma separated string from mysql query

phpmysqlarraysstringimplode

提问by dll_onFire

For the last 1 1/2 days I've been trying to store 16 row id's into a string and separate each id with a comma. The array I am getting is from MySQL. The error I am getting is

在过去的 1 1/2 天里,我一直在尝试将 16 个行 ID 存储到一个字符串中,并用逗号分隔每个 ID。我得到的数组来自 MySQL。我得到的错误是

implode() function:passed invalid arguments

implode() 函数:传递了无效参数

$str=array();
$string="";
while($row = mysql_fetch_row($result)) 
{
    $user_id=$row;
    $str=$user_id;
    foreach($str as $p=>$v){
        comma($v);
    }
}

function comma($v){
    $string= implode(",",$v); echo $string;
}

回答by huysentruitw

Try something like this:

尝试这样的事情:

$ids = array(); 
while ($row = mysql_fetch_assoc($result))  
{
    $ids[] = $row["UserID"]; 
} 
echo implode(", ", $ids);

Replace "UserID"with the columnname of the id in your table.

替换"UserID"为表中 id 的列名。

So: first you build the array, next you implode the array into a string.

所以:首先构建数组,然后将数组内爆为字符串。

回答by perfectio

There is my solution:

有我的解决方案:

SELECT GROUP_CONCAT(UserID) as string  FROM Users;

For this function the delimiter is ',' by default.

对于此函数,分隔符默认为“,”。

回答by Darwin

$query = 'SELECT id FROM your_table';
$rs = mysql_query($query);

$row = mysql_fetch_array($result);
return implode(',', $row);

the result 1,2,3...

结果 1,2,3...