Parsing JSON in PHP

前端 未结 2 1322
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 10:27

I´ve got the following JSON string:

{\"Data\":{\"Recipes\":{\"Recipe_5\":{\"ID\":\"5\",\"TITLE\":\"Spaghetti Bolognese\"},\"Recipe_7\":{\"ID\":\"7\",\"TITLE         


        
相关标签:
2条回答
  • 2020-12-22 11:14

    You can use the function json_decode to parse JSON data in PHP (>= 5.2.0, at least). Once you have a PHP object, it should be easy to iterate over all recipes/members and access their titles, using something like this:

    $data = json_decode($json, true); // yields associative arrays instead of objects
    foreach ($data['Data']['Recipes'] as $key => $recipe) {
        echo $recipe['TITLE'];
    }
    

    (Sorry I can't actually run this code right now. Hope it helps anyway.)

    0 讨论(0)
  • 2020-12-22 11:14

    If you want to do that in JavaScript, you can simply access JSON data like "normal" objects:

    var jsonData = {
        "Data": {"Recipes": {"Recipe_5": {"ID":"5","TITLE":"Spaghetti Bolognese"}}}
        // more data
    };
    alert(jsonData.Data.Recipes.Recipe_5.TITLE);
    

    This will print the TITLE of Recipe_5 in a message box.

    EDIT:

    If you want all the titles in a list, you can do something like this:

    var titles = [];
    for (var key in jsonData.Data.Recipes) {
        var recipe = jsonData.Data.Recipes[key];
        titles.push(recipe.TITLE);
    }
    alert(titles);
    
    0 讨论(0)
提交回复
热议问题