简体   繁体   English

合并Mysql列输出,以逗号分隔在php中

[英]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. 我只希望将其作为PHP中的数组,并将它们用逗号分隔。

So I did, 所以我做了,

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

and its working if I echo it with print_r 和它的工作,如果我用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 $ rows [0]给我一个词'Array'

echo implode(",", $rows); echo implode(“,”,$ rows); gives me 1Array',Array1 给我1Array',Array1

I tried 我试过了

echo json_encode($rows[0]);

gives me 给我

["1"]

I simply want 1,2 我只想要1,2

After a lot of different tries I gave up and added group_concat in the sql query. 经过多次尝试,我放弃了,并在sql查询中添加了group_concat。 I just want to know what I did wrong. 我只想知道我做错了什么。

Thanks. 谢谢。

mysql_fetch_row i returning a single element array. mysql_fetch_row我返回单个元素数组。 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){ 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....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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