How to convert an array of values ​​returned from a query to comma separated values

I have a result set that is returned using this code:

while ($row = mysql_fetch_array( $result )) { echo "ID ".$row['v2id']; } 

it returns ID 2ID 3ID 4ID 8

how would I convert this to comma separated values ​​and then store them in a variable?

therefore, if I chose a variable, the final result should look like 2, 3, 4, 8

+7
source share
5 answers

save all the values ​​in an array, then attach them using "," as glue

 $values = array(); while ($row = mysql_fetch_array( $result )) { $values[] = $row['v2id']; } echo join(", ", $values); 
+6
source

Add all the values ​​to the array, then implode using ', ' as glue

 $result = array(); while ($row = mysql_fetch_array($result)) { $result[] = $row['v2id']; } echo implode(', ', $result); 
+1
source
 $data = array(1,2,'Hello',3,4,'1,234.56'); $outstream = fopen("php://temp", 'r+'); fputcsv($outstream, $data, ',', '"'); rewind($outstream); $csv = fgets($outstream); fclose($outstream); 
+1
source
 $ids = array(); while ($row = mysql_fetch_array( $result )) { $ids[] = (int)$row['v2id']; } echo implode(", ", $values); 

1ID 2ID 3ID 4ID 8 can be converted to int by (int) $ row ['v2id'], so $ ids will only contain int.

+1
source

My way would be like this

  $ csv = '';
 while ($ row = mysql_fetch_array ($ result)) {
    / * Note the '. =' - appends variable * /
    $ csv. = "ID". $ row ['v2id'];
    $ csv. = ',';  // This is the bit I missed out
 }
 / * Remove the final trailing comma * /
 $ csv = substr ($ csv, 0, -1);
 echo $ csv; 

The golden star goes into ssapkota to determine the "intentional" error p>

0
source

All Articles