格式化json数据。如何合并具有相同值的json数组?

时间:2016-05-14 20:17:47

标签: php mysql json codeigniter

抱歉,如果我的问题有点混乱。 以下是我的json输出形式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"}]

我想利用这一天"星期日"在这种情况下,将两个对象合并为以下形式:

"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"]
        }

    ]

另外,是否有任何工具可以帮助我在php中制作模型以将其保存在数据库中?

提前感谢。

最大

2 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

$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);

答案 1 :(得分:1)

您可以在PHP中重新组织它,如其他答案所示。您也可以在Javascript中重新组织它:

var values = [{"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"}];

var final = {};
values.forEach(function(element, index, array) {
    if (!final[element.Day]) 
        final[element.Day] = [];

    final[element.Day].push(
        {
            "low": element.Low,
            "high": element.High,
            "mid": element.Mid.split(" ")
        }
    );
});