Imagine each row as X axis and each column as a series (a line in the chart):
---------------------------------
year | apple_price | banana_price
---------------------------------
2010 2.5 1.7
2011 2.6 2.0
array // MySQL results set
0 =>
array
'year' => 2010
'apple_price' => 2.5
'banana_price' => 1.7
1 =>
array
'year' => 2011
'apple_price' => 2.6
'banana_price' => 2.0
I need to transform mysql array to something more suitable for my charts API and JSON. How would you implement this? Would be possible to transpose the results set? EDIT: this of course should be dynamic: first column is X axis, the remain will be the series (lines in the chart):
array // indexed
0 =>
array // associative
'name' => 'apple_price'
'data' => [[2010, 2.5], [2011, 2.6]] // indexed array of array
1 =>
array // associative
'name' => 'banana_price'
'data' => [[2010, 1.7], [2011, 2.0]] // indexed array of array
EDIT: first quick and dirty working solution, trying to get a better one:
public static function mysqlResultSetToChartSeries($data)
{
// Return empty array if 0 rows or columns < 2
if (!isset($data[0]) || !count($data[0]) > 1) return array();
// Get all keys (columns names)
$keys = array_keys($data[0]);
// Temp array for storing col names and values
$tmp = array();
foreach($keys as $k) $tmp[$k] = array_map(function($r) use ($k){
return $r[$k];
}, $data);
// X axis
$x = array_shift($tmp);
$series = array_map(function($k, $v) use ($x) {
return array(
'name' => $k,
'data' => array_map(function($xaxis, $yaxis) use ($x) {
return array($xaxis, $yaxis);
}, array_values($x), $v)
);
}, array_keys($tmp), array_values($tmp));
return $series;
}
The class:
To use:
Notes: