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 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低