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 數組一樣存取該數組的各個元素。