dongshi7433 2016-05-14 20:17
浏览 146
已采纳

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

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

  • 写回答

2条回答 默认 最新

  • dongxian3418 2016-05-14 20:30
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c