简体   繁体   中英

Merge Mysql Column output as comma seperated in php

I have a simple query with outputs only one column (rows number may change)

SELECT column1 as NUMBER WHERE column1 ...

Output,

NUMBER
  1
  2

I just want it as an array in PHP with them as comma seperated.

So I did,

$rows = array();
while ($row = mysql_fetch_row($result)) {
    $rows[] = $row;

and its working if I echo it with print_r

However because of some reason I cant get the plain values out of this array.

echo $rows[0] gives me the word 'Array'

echo implode(",", $rows); gives me 1Array',Array1

I tried

echo json_encode($rows[0]);

gives me

["1"]

I simply want 1,2

After a lot of different tries I gave up and added group_concat in the sql query. I just want to know what I did wrong.

Thanks.

mysql_fetch_row i returning a single element array. To have your desired output, only select the 1st element:

$rows = array();
while ($row = mysql_fetch_row($result)) {
    $rows[] = $row[0];

foreach($rows as $key => $value){

}

should do the trick, with an echo it will output the results as an associative array

just make a simple amendment to your code:

$rows[] = $row;

into:

$rows[] = $row[0];

and use:

implode(", ", $rows[]);

尝试这个

SELECT GROUP_CONCAT(`column1` SEPARATOR ',') AS number FROM table where....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM