Maxxer Maxxer - 1 year ago 98
SQL Question

formating json data. how to merge json array with same value as key?

sorry if my question is little confusing.
the following is my json output form mysql:

[{"ID":"2","BatchID":"0","Day":"Sunday","Low":"01:15","High":"02.45","Mid": "01:30 01:45 02:00 02:15 02:30"}, {"ID":"1","BatchID":"0","Day":"Sunday","Low":"00.45","High":"00:30","Mid":" 01:30 01:45 02:00 02:15 02:30"}]

i want to use the day "sunday" in this case to merge both the objects to form something like this:



also, are there any tools that can help me make models in php for saving this in a db?

thanks in advance.


Answer Source

You can use something like :

$data = json_decode($mysql_data, true);
$res = [];
foreach ($data as $d)
    $add = ['low'  => $d['Low'],
            'high' => $d['High'],
            'mid'  => explode(' ', trim($d['Mid']))];
    if (!isset($res[$d['Day']]))
        $res[$d['Day']] = $add;
        $res[$d['Day']][] = $add;
$pretty_data = json_encode($res);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download