如何使用 PHP 从 JSON 中提取和访问数据? [英] How to extract and access data from JSON with PHP?

查看:66
本文介绍了如何使用 PHP 从 JSON 中提取和访问数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

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

我有 JSON:

<代码>{类型":甜甜圈","name": "蛋糕",浇头":[{ "id": "5002", "type": "Glazed" },{ "id": "5006", "type": "巧克力酱" },{ "id": "5004", "type": "Maple" }]}

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

解决方案

Intro

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

 $data = json_decode($json);

您可能会发现:

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

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

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

<小时>

访问对象属性

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

$json = '{类型":甜甜圈",名称":蛋糕"}';$yummy = json_decode($json);echo $yummy->type;//甜甜圈

<小时>

访问数组元素

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

$json = '["釉色",洒上巧克力",枫"]';$toppings = json_decode($json);回声$浇头[1];//洒上巧克力

使用 foreach 对其进行迭代.

foreach ($toppings as $topping) {回声 $顶部, "
";}

<块引用>

釉面
巧克力碎
枫木

或者使用任何无数的内置数组函数.

<小时>

访问嵌套项

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

$json = '{类型":甜甜圈","name": "蛋糕",浇头":[{ "id": "5002", "type": "Glazed" },{ "id": "5006", "type": "巧克力酱" },{ "id": "5004", "type": "Maple" }]}';$yummy = json_decode($json);回声 $yummy->toppings[2]->id;//5004

<小时>

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

当你这样做时,你会得到关联数组而不是对象——带有键字符串的数组.您再次像往常一样访问其中的元素,例如$array['key'].

$json = '{类型":甜甜圈","name": "蛋糕",浇头":[{ "id": "5002", "type": "Glazed" },{ "id": "5006", "type": "巧克力酱" },{ "id": "5004", "type": "Maple" }]}';$yummy = json_decode($json, true);echo $yummy['配料'][2]['type'];//枫

<小时>

访问关联数组项

将 JSON 对象 解码为关联 PHP 数组时,您可以使用 foreach (array_expression as $key => $value) 语法,例如

$json = '{"foo": "foo 值","bar": "bar 值","baz": "baz 值"}';$assoc = json_decode($json, true);foreach ($assoc as $key => $value) {echo "key '$key' 的值为 '$value'", PHP_EOL;}

印刷品

<块引用>

key 'foo' 的值为 'foo value'
键 'bar' 的值为 'bar value'
key 'baz' 的值是 'baz value'

<小时>

不知道数据的结构

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

看看 JSON - 你看到大括号 {} 期望一个对象,你看到方括号 [] 期望一个数组.

使用print_r()点击解码数据:

$json = '{类型":甜甜圈","name": "蛋糕",浇头":[{ "id": "5002", "type": "Glazed" },{ "id": "5006", "type": "巧克力酱" },{ "id": "5004", "type": "Maple" }]}';$yummy = json_decode($json);print_r($yummy);

并检查输出:

stdClass 对象([类型] =>甜甜圈[名称] =>蛋糕[浇头] =>大批([0] =>标准类对象([id] =>5002[类型] =>釉面)[1] =>标准类对象([id] =>5006[类型] =>洒巧克力)[2] =>标准类对象([id] =>5004[类型] =>枫)))

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

如果你只能在迷路之前深入了解它 - 走那么远并使用 print_r() 击中那个:

print_r($yummy->toppings[0]);

stdClass 对象([id] =>5002[类型] =>釉面)

这个方便的交互式 JSON 浏览器中查看它.

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

<小时>

json_decode() 返回 null

发生这种情况是因为:

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

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

<小时>

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

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

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

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

<小时>

有人将 JSON 放入你的 JSON

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

$json = '{类型":甜甜圈","name": "蛋糕","配料": "[{ "type": "Glazed" }, { "type": "Maple" }]"}';$yummy = json_decode($json);$toppings = json_decode($yummy->toppings);echo $toppings[0]->type;//上釉

<小时>

数据不适合内存

如果您的 JSON 太大而 json_decode() 无法立即处理,事情就会开始变得棘手.见:

<小时>

如何排序

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

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.

I have the JSON:

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

How do I decode this in PHP and access the resulting data?

解决方案

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

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

$yummy = json_decode($json);

echo $yummy->type; //donut


Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

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

$toppings = json_decode($json);

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

Iterate over it with foreach.

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

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $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()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $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


Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

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

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a 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);

and check the output:

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
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);

stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

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

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

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

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

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

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


Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:


How to sort it

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

这篇关于如何使用 PHP 从 JSON 中提取和访问数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆