首页  >  问答  >  正文

如何使用 PHP 从 JSON 中提取和访问数据?

<p><br /></p><blockquote> <p>这是一个通用参考问题和答案,涵盖许多永无休止的“如何访问 JSON 中的数据?”问题。它在这里处理在 PHP 中解码 JSON 并访问结果的广泛基础知识。</p> </blockquote> <p>我有 JSON:</p> <pre class="brush:php;toolbar:false;">{ "type": "donut", "name": "Cake", "toppings": [ { "id": "5002", "type": "Glazed" }, { "id": "5006", "type": "Chocolate with Sprinkles" }, { "id": "5004", "type": "Maple" } ] }</pre> <p>如何在 PHP 中对其进行解码并访问结果数据?</p>
P粉099985373P粉099985373445 天前470

全部回复(1)我来回复

  • P粉388945432

    P粉3889454322023-08-24 09:10:33

    <?php
    $jsonData = '{
        "type": "donut",
        "name": "Cake",
        "toppings": [
            { "id": "5002", "type": "Glazed" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5004", "type": "Maple" }
        ]
    }';
    
    // Decode the JSON
    $data = json_decode($jsonData, true);
    
    // Access the data
    $type = $data['type'];
    $name = $data['name'];
    $toppings = $data['toppings'];
    
    // Access individual topping details
    $firstTopping = $toppings[0];
    $firstToppingId = $firstTopping['id'];
    $firstToppingType = $firstTopping['type'];
    
    // Print the data
    echo "Type: $type\n";
    echo "Name: $name\n";
    echo "First Topping ID: $firstToppingId\n";
    echo "First Topping Type: $firstToppingType\n";
    ?>

    在此示例中,json_decode() 用于将 JSON 数据解码为 PHP 关联数组。然后,您可以像访问任何 PHP 数组一样访问该数组的各个元素。

    回复
    0
  • 取消回复