I have a result set that is being returned using this code:
while ($row = mysql_fetch_array( $result )) {
ech开发者_运维百科o "ID ".$row['v2id'];
}
this returns ID 2ID 3ID 4ID 8
how would i convert this to comma separated values and then store them in a variable?
so if i echoed out the variable, the final output would should look like 2, 3, 4, 8
store all the values in an array, then join them using ", " as the glue
$values = array();
while ($row = mysql_fetch_array( $result )) {
$values[] = $row['v2id'];
}
echo join(", ", $values);
Add all to values to an array, then implode it using ', '
as glue
$result = array();
while ($row = mysql_fetch_array($result)) {
$result[] = $row['v2id'];
}
echo implode(', ', $result);
$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);
$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 contain int only.
My way would be 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 gold star for spotting the 'deliberate' mistake goes to ssapkota
精彩评论