chapskev chapskev - 6 months ago 26
JSON Question

PHP array reformat to highchart json ob

I am try to format an array to a JSON object that highcharts supports. My array from the database is as follows:

Array
(
[0] => Array
(
[Group_ID] => 1
[Name] => A line graph
[month] => 4
[amount] => 7700
)

[1] => Array
(
[Group_ID] => 2
[Name] => B Line graph
[month] => 4
[amount] => 390
)

[2] => Array
(
[Group_ID] => 1
[Name] => A line graph
[month] => 5
[amount] => 5000
)

[3] => Array
(
[Group_ID] => 2
[Name] => B line graph
[month] => 5
[amount] => 210
)
)


I need to create an array like this to be able to create a highchart compatible JSON object:

Array
(
[0] => Array
(
[name] => A revenue
[data] => Array
(
[4] => 7700 //amount for the fourth month
[5] => 5000 //amount for the fifth month
)
)

[1] => Array
(
[name] => B revenue
[data] => Array
(
[4] => 390 //amount for the fourth month
[5] => 210 //amount for the fifth month
)
)
)


I have managed to come up with this array using my foreach but I cant seem to find a way to do it correctly:

Array
(
[0] => Array
(
[name] => A line graph
[amount] => 7700
[month] => 4
)

[1] => Array
(
[name] => B line graph
[amount] => 390
[month] => 4
)

[2] => Array
(
[name] => A line graph
[amount] => 5000
[month] => 5
)

[3] => Array
(
[name] => B line graph
[amount] => 210
[month] => 5
)

)


My foreach:

foreach ($data as $key => $value) {
$r[] = [
'name' => $value['Line_GraphName'],
'data' => $value['amount'],
'month' => $value['month']
];
}

Answer

You can create it very simply like this:

foreach ($data as $value) {
    $r[$value['Group_ID']]['name'] = $value['Line_GraphName']; 
    $r[$value['Group_ID']]['data'][$value['month']] = $value['amount'];
}
  • Loop and create a result with Group_ID as the key and add the name key and value
  • Add data array and append month as key and amount as value

If you don't like having Group_ID as the key and want to re-index:

$r = array_values($r);
Comments