views:

82

answers:

2

Hi guys,

I would like to output my php array into this format: [1991, 6.5], [1992, 4], [1993, 5.9]

PHP array:

while ($row = mysqli_fetch_array($result))
{
  $metals[] = array('year' => $row['year'], 
                    'metal' => $row['metal'];
}

I have seen some examples of implode function but I couldn't find any that could match what I want to do.

Thanks for your help.

+1  A: 

Try

$tmp = array();
foreach($metals as $metal){
    $tmp[] = '['.implode(",", $metal).']';
}
$formatted_output = implode(",", $tmp);
print_r($formatted_output);
Mithun P
the output becomes [array, array, array, array, array],[array, array, array, array, array]. I have no idea how it becomes 5 elements in a single array.
dave
A: 

My crystal ball suggests you want to generate JSON for an AJAX thingie. If so, i's as easy as this:

<?php

$metals = array();
$metals[] = array(1991, 6.5);
$metals[] = array(1992, 4);
$metals[] = array(1993, 5.9);

echo json_encode($metals);

?>

Which prints:

[[1991,6.5],[1992,4],[1993,5.9]]
Álvaro G. Vicario
ummmmmmm........
Mithun P
Hi Alavaro, you are right about what I plan to do. However, I have more hundreds of records. I'm looking at the direction of creating a while loop to output data in that format. Is there anyway to do that?
dave
And how do you go about removing the quotes from within. Currently, I have ["1991", "5.6"], ["1992", "6"]. Thanks Alvaro.
dave
That's because those values are strings. Cast them to integers or floats when reading them: `(int)$foo`, `(float)$bar`
Álvaro G. Vicario