gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:15:00 26 4
gpt4 key购买 nike

This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.

我有 JSON:

{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}

如何在 PHP 中对其进行解码并访问结果数据?

最佳答案

<?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 数组一样访问该数组的各个元素。

关于php - 如何使用 PHP 从 JSON 中提取和访问数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50385207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com