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条)

报告相同问题?