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

use*_*918 198 php json

这是一个一般参考问题和答案,涵盖了许多永无止境的"如何访问我的JSON中的数据?" 的问题.它可以处理在PHP中解码JSON和访问结果的广泛基础知识.

我有JSON:

{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}
Run Code Online (Sandbox Code Playgroud)

如何在PHP中解码并访问结果数据?

use*_*918 391

介绍

首先,你有一个字符串.JSON不是数组,对象或数据结构.JSON是一种基于文本的序列化格式 - 所以是一个奇特的字符串,但仍然只是一个字符串.使用PHP在PHP中解码json_decode().

 $data = json_decode($json);
Run Code Online (Sandbox Code Playgroud)

在那里你可能会发现:

这些是可以用JSON编码的东西.或者更准确地说,这些是可以用JSON编码的PHP版本.

他们没什么特别的.它们不是"JSON对象"或"JSON数组".您已经解码了JSON - 您现在拥有基本的日常PHP类型.

对象将是stdClass的实例,这是一个内置类,它只是一个通用的东西,在这里并不重要.


访问对象属性

您访问的属性,这些对象之一,你会为任何其他对象,如公共非静态属性的方法相同$object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut
Run Code Online (Sandbox Code Playgroud)

访问数组元素

您可以像访问任何其他数组一样访问其中一个数组的元素,例如$array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles
Run Code Online (Sandbox Code Playgroud)

用它来迭代它foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}
Run Code Online (Sandbox Code Playgroud)

釉面
巧克力撒上
枫树

或者搞乱任何一个数以亿计的内置数组函数.


访问嵌套项

对象的属性和数组的元素可能是更多的对象和/或数组 - 您可以像往常一样继续访问其属性和成员,例如$object->array[0]->etc.

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

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004
Run Code Online (Sandbox Code Playgroud)

true作为第二个参数传递给json_decode()

当你这样做时,你将获得关联数组而不是对象 - 带有键的字符串的数组.您可以像往常一样访问其元素,例如$array['key'].

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

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple
Run Code Online (Sandbox Code Playgroud)

不知道数据的结构

阅读文档,了解您从中获取JSON的任何内容.

看看JSON - 你看到花括号foreach (array_expression as $key => $value)期望一个对象,你看到方括号{}期望一个数组.

点击解码数据[]:

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)

并检查输出:

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

$yummy = json_decode($json);

print_r($yummy);
Run Code Online (Sandbox Code Playgroud)

它会告诉你在哪里有对象,你有数组的位置,以及它们的成员的名字和值.

如果你只能得到这么远到它,你迷路之前-走那么远,打的是print_r():

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)
Run Code Online (Sandbox Code Playgroud)
print_r($yummy->toppings[0]);
Run Code Online (Sandbox Code Playgroud)

这个方便的交互式JSON资源管理器中查看它.

将问题分解成更容易缠绕的部分.


print_r() 回报 json_decode()

发生这种情况是因为:

  1. JSON完全由此组成null.
  2. JSON无效 - 检查结果null或通过JSONLint之类的东西.
  3. 它包含嵌套超过512级深度的元素.可以通过将整数作为第三个参数传递来覆盖此默认最大深度json_last_error_msg.

如果你需要改变最大深度,你可能正在解决错误的问题.找出你为什么得到如此深层嵌套的数据(例如,你正在查询生成JSON的服务有一个bug)并且不会发生这种情况.


对象属性名称包含特殊字符

有时,您将拥有一个对象属性名称,其中包含连字符json_decode()或符号-,不能在文字标识符中使用.相反,您可以在花括号内使用字符串文字来解决它.

stdClass Object
(
    [id] => 5002
    [type] => Glazed
)
Run Code Online (Sandbox Code Playgroud)

如果您有一个整数作为属性,请参阅:如何使用整数等名称访问对象属性?作为参考.


有人把JSON放在你的JSON中

这很荒谬,但它发生了 - JSON编码为JSON中的字符串.解码,访问字符串像往常一样,解码认为,最终得到你所需要的.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42
Run Code Online (Sandbox Code Playgroud)

数据不适合内存

如果你的JSON太大而@无法立即处理,事情开始变得棘手.看到:


如何排序

请参阅:参考:在PHP中对数组和数据进行排序的所有基本方法.


Moh*_*jib 17

您可以使用json_decode()将json字符串转换为PHP对象/数组.

例如.

输入:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));
Run Code Online (Sandbox Code Playgroud)

输出:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
Run Code Online (Sandbox Code Playgroud)

几点要记住:

  • json_decode要求字符串是有效的,json否则它将返回NULL.
  • 如果解码失败,json_last_error()可用于确定错误的确切性质.
  • 确保传入utf8内容,或者json_decode可能出错并只返回一个NULL值.

  • @Isaac当一些人想要开始使用该功能时,可能不会非常热衷于阅读整本手册.否则他们最好不要阅读官方文件.SO的重点在于提供答案的简单性.恕我直言 (3认同)

小智 5

<?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";
?>
Run Code Online (Sandbox Code Playgroud)

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


归档时间:

查看次数:

248624 次

最近记录:

5 年,10 月 前