Rumah > Soal Jawab > teks badan
P粉6814003072023-08-29 09:39:34
<?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"; ?>
Dalam contoh ini, json_decode() digunakan untuk menyahkod data JSON ke dalam tatasusunan bersekutu PHP. Anda kemudiannya boleh mengakses elemen individu tatasusunan seperti mana-mana tatasusunan PHP.