implode an array into a comma separated string from mysql query

独自空忆成欢 提交于 2019-12-10 02:14:06

问题


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

implode() function:passed invalid arguments

$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;
}

回答1:


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.

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




回答2:


There is my solution:

SELECT GROUP_CONCAT(UserID) as string  FROM Users;

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




回答3:


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

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

the result 1,2,3...



来源:https://stackoverflow.com/questions/11599917/implode-an-array-into-a-comma-separated-string-from-mysql-query

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