这是一个一般性的参考问题和答案,涵盖了"How do I access data in my JSON?"个永无止境的问题中的许多.这里介绍了在PHP中解码JSON和访问结果的基本知识.

我有JSON:

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

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

推荐答案

简介

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

 $data = json_decode($json);

你可能会发现:

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

他们没什么特别的.它们不是"JSON对象"或"JSON数组"你已经解码了JSON,现在你有basic everyday PHP types个了.

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


访问对象属性

访问其中一个对象的properties的方式与访问任何其他对象(例如$object->property)的公共非静态属性的方式相同.

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

$yummy = json_decode($json);

echo $yummy->type; //donut

访问数组元素

访问其中一个数组的元素的方式与访问任何其他数组(例如$array[0])的方式相同.

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

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

foreach重复它.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

也不能和bazillion built-in array functions个人中的任何一个打交道.


访问嵌套项

对象的属性和数组的元素可能是更多的对象和/或数组-您可以像往常一样继续访问它们的属性和成员,例如$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

Passing true as the second argument to json_decode()

当您这样做时,您将得到关联数组,而不是对象-带有键字符串的array.同样,您可以像往常一样访问其中的元素,例如$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

访问关联数组项

将JSON object解码为关联PHP数组时,可以使用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;
}

输出

键‘foo’的值是‘foo value’
键‘bar’的值是‘bar value’
密钥"baz"的值是"baz value"


我不知道数据是如何组织的

阅读文档,了解JSON的来源.

看看JSON——你看到花括号{}表示对象,方括号[]表示array.

print_r():

$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);

并判断输出:

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
                )

        )

)

它将告诉您在哪里有对象,在哪里有数组,以及它们的成员的名称和值.

如果你在迷路前只能走这么远——走那么远,用print_r()that:

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

请在this handy interactive JSON explorer分钟内看一看.

把问题分解成更容易理解的部分.


json_decode() returns null

这是因为:

  1. JSON完全由null个元素组成.
  2. JSON无效-请判断json_last_error_msg的结果,或将其置于类似JSONLint的位置.
  3. 它包含嵌套超过512层的元素.通过将整数作为第三个参数传递给json_decode(),可以覆盖默认的最大深度.

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


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

有时,对象属性名包含连字符-或at符号@之类的内容,不能在文字标识符中使用.相反,您可以使用大括号内的字符串文字来解决它.

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

echo $thing->{'@attributes'}->answer; //42

如果您有一个整数作为属性,请参见:How to access object properties with names like integers?作为参考.


有人在你的JSON中加入了JSON

这很荒谬,但确实发生了——JSON中有一个字符串编码的JSON.解码,像往常一样访问字符串,解码that,最终得到你需要的.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

数据无法存储在内存中

如果您的JSON太大,无法同时处理json_decode()个,那么事情就会变得棘手起来.请参见:


如何分类

见:Reference: all basic ways to sort arrays and data in PHP.

Php相关问答推荐

Postgrid Webhook不叫laravel

将下拉 Select 的值从WooCommerce后端保存并显示到前端

在WooCommerce管理中 for each 运输方法设置添加自定义字段

在PHP中使用curl命令执行SCRAPYD操作.json不返回任何内容

如果日期是过go 日期,则隐藏事件发布类型

PHP:使用FORT从数据库获取USERS表到AUTH表

Regex:高级删除单行PHP注释

WooCommerce中特定付款方式的变更订单预留库存时间

Woocommerce 仅在前端为登录用户提供价格折扣

PHP Laravel 迁移文件不创建关系

PHP:数组的等边

产品页面自定义复选框可对 WooCommerce 购物车小计启用百分比折扣

添加产品标签以通过 WooCommerce 邮箱通知订购商品

如何将文件上传添加到 WooCommerce 结帐?

Windows 身份验证在 IIS 中验证什么?我可以在我的情况下禁用匿名身份验证吗?

使用其ID查询和捕获与订单相关的其他详细信息的shopware 6方法

优化后的标题:如何在WooCommerce我的帐户编辑表单中添加账单字段

PHP Loop 在迭代中使用修改后的数据

如何正确使用Flysystem和Local Adapter

使用 PHP ImageMagick 库将 pdf 文件的前 n 页转换为单个 png 图像文件