简体   繁体   中英

convert some records to comma separated array

I have table like this:

table Database
+------+--------------+
| name | data         |
+------+--------------+
| foo  | certaindata1 |
| bar  | certaindata2 |
| foo  | certaindata3 |
+------+--------------+

and I want to output data for array values like: array('certaindata1','certaindata2','certaindata3')

I have try this

$sql = mysql_query("SELECT data FROM Database");
while($row=mysql_fetch_array($sql)){
     echo $row['data'];
}

and result is certaindata1certaindata2certaindata3
where array value should be 'certaindata1','certaindata2','certaindata3'

The result is expected. You're simply echoing $row['data']; without any spaces or newlines -- so the result will be certaindata1certaindata2certaindata3 . If you want to store the results in an array, you can do the following:

while($row=mysql_fetch_array($sql)){
     $yourArray[] = $row['data']; //storing the $row['data'] in an array
}
$comma_separated = implode(',', $yourArray);
print_r($comma_separated);

Hope this helps!

You should use implode() to make it comma separated..

while($row=mysql_fetch_array($sql)){
     $yourArray[] = $row['data']; //storing the $row['data'] in an array
}
$result = implode(",", $yourArray);

print_r($result);

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