James Rand
James Rand

Reputation: 117

how do i convert a array of values returned from a query to comma separated values

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

while ($row = mysql_fetch_array( $result )) {

echo "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

Upvotes: 7

Views: 579

Answers (5)

MrSimonEmms
MrSimonEmms

Reputation: 1481

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

Upvotes: 0

user787034
user787034

Reputation:

$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.

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212402

$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);

Upvotes: 1

Petah
Petah

Reputation: 46040

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);

Upvotes: 1

bumperbox
bumperbox

Reputation: 10214

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);

Upvotes: 6

Related Questions