douluhaikao93943 2016-11-17 04:15
浏览 176
已采纳

如何解码PHP中的JSON嵌套数组值?

So I have this JSON string:

"{"Jan": [5, 10, 15, 20] , 
  "Feb":[20,10,"",22], 
  "Mar":[5,3,"",4], 
  "April":[10,"",1,2]
 }, 
 {"title":"Test Chart - Month v Value"}"

I am trying to extract the data so that I can access each one so that I can iterate through the array and sequentially output the data.

The best way I can think of is to simply create an array of arrays in PHP, store key and its values together and do a nested for loop. So the array should look like this:

[[Jan, 5, 10, 15, 20],[Feb, 20, 10, ,22], [Mar, 5, 3, , 4]]

Lastly I would like to know how to store this title value into its own variable.

  • 写回答

4条回答 默认 最新

  • dpa31905 2016-11-17 04:22
    关注

    Your string isn't valid json currently, but it does contain two valid json strings. The json_decode() function won't work on your string as-is, but it does work on each individual valid json string:

    <?php
    
    // INVALID JSON STRING - THIS WON'T WORK:
    $json = '{"Jan": [5, 10, 15, 20] , "Feb":[20,10,"",22], "Mar":[5,3,"",4], "April":[10,"",1,2]}, {"title":"Test Chart - Month v Value"}';
    print_r(json_decode($json));
    
    // This works:
    $json = '{"Jan": [5, 10, 15, 20] , "Feb":[20,10,"",22], "Mar":[5,3,"",4], "April":[10,"",1,2]}';
    print_r(json_decode($json));
    
    // This works:
    $json = '{"title":"Test Chart - Month v Value"}';
    print_r(json_decode($json));
    
    ?>
    

    Ideally you would fix the source json, but it might be getting passed to you or retrieved from a system you have no control over.

    If you can safely assume that the json will always have a structure like in your example, you could split the strings out doing something like this:

    if (preg_match_all("/{[^}]*}/", $str, $matches)) {
      foreach ($matches[0] AS $json) {
        print_r(json_decode($json));
      }
    }
    

    This won't work if the json object contains other objects, which is why it depends on whether you can safely assume the structure will always be the same or not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测