PHP JSON Array - Group by the same value -
i'm thinking how group array objects same value.
i have result mysql query:
date starttime endtime 2014-12-01 08:00 12:00 2014-12-01 10:00 16:00 2014-12-02 12:00 18:00 2014-12-03 10:00 20:00
i have data in php variable called $data
.
is possible json array php: ?
[ { "2014-12-01": [ { "starttime": "08:00", "endtime": "12:00" }, { "starttime": "10:00", "endtime": "16:00" } ] }, { "2014-12-02": [ { "starttime": "12:00", "endtime": "18:00" } ] }, { "2014-12-03": [ { "starttime": "10:00", "endtime": "20:00" } ] } ]
if use echo json_encode($data)
, result is:
[ { "date": "2014-12-01", "starttime": "10:00", "endtime": "16:00" }, { "date": "2014-12-02", "starttime": "12:00", "endtime": "18:00" }, { "date": "2014-12-03", "starttime": "10:00", "endtime": "20:00" } ]
based on structure outlined in question:
requires php 5.4+ json pretty printing, if on lower version remove , use long array format.
$in = <<<'json' [ { "date": "2014-12-01", "starttime": "10:00", "endtime": "16:00" }, { "date": "2014-12-02", "starttime": "12:00", "endtime": "18:00" }, { "date": "2014-12-03", "starttime": "10:00", "endtime": "20:00" }, { "date": "2014-12-03", "starttime": "12:00", "endtime": "20:00" } ] json; $data = json_decode($in, true); $out = []; foreach($data $element) { $out[$element['date']][] = ['starttime' => $element['starttime'], 'endtime' => $element['endtime']]; } var_dump(json_encode($out, json_pretty_print));
to exact same output in question (the returned output wrapped in single element json-array you'd need wrap $out
in other array this:
json_encode([$out], json_pretty_print)
results in:
{ "2014-12-01": [ { "starttime": "10:00", "endtime": "16:00" } ], "2014-12-02": [ { "starttime": "12:00", "endtime": "18:00" } ], "2014-12-03": [ { "starttime": "10:00", "endtime": "20:00" }, { "starttime": "12:00", "endtime": "20:00" } ] }
Comments
Post a Comment