Maxxer Maxxer - 6 months ago 14
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:

"Sunday":[
{
"low":"00:15",
"high":"00.45",
"mid":["00:30"]
},
{
"low":"01:15",
"high":"02.45",
"mid":["01:30","01:45","02:00","02:15","02:30"]
}

]


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

thanks in advance.

max

Answer

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;
    else
        $res[$d['Day']][] = $add;
}
$pretty_data = json_encode($res);
Comments