简体   繁体   English

PHP JSON与孩子一起解码

[英]Php json decode with child

I been looking thru the posts here all day but can't figure out what I'm doing wrong. 我整天都在浏览这些帖子,但无法弄清楚我在做什么错。 (I'm new to php and json) (我是php和json的新手)

Here is my code that work. 这是我的工作代码。

    $json = '{"id":1234,"img":"1.jpg"}';
    $data = json_decode($json, true);
    echo $data["img"];

But when the json respond is this 但是当json响应是这个

    $json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';

it's a big harder for me. 这对我来说很难。 then img is a child of demo1? 那么img是demo1的孩子吗? How to get it? 如何获得?

Thx. 谢谢。 :) :)

Figuring out the array indices 找出数组索引

As you're new to PHP, I'll explain how to figure out the array indces of the required array value. 当您不熟悉PHP时,我将解释如何计算所需数组值的数组索引。 In PHP, there are many functions for debugging — print_r() and var_dump() are two of them. 在PHP中,有许多用于调试的函数print_r()var_dump()是其中两个。 print_r() gives us a human-readable output of the supplied array, and var_dump() gives us a structured output along with the variable types and values. print_r()为我们提供了所提供数组的可读输出,而var_dump()为我们提供了结构化输出以及变量类型和值。

In this case, print_r() should suffice: 在这种情况下, print_r()应该足够了:

$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
$data = json_decode($json, true);

// wrap the output in <pre> tags to get a prettier output

echo '<pre>';
print_r($data);
echo '</pre>';

This will produce the following output: 这将产生以下输出:

Array
(
    [demo1] => Array
        (
            [0] => Array
                (
                    [id] => 1234
                    [img] => 1.jpg
                )

        )

    [userId] => 1
)

From there, it should be pretty easy for you to figure out how to access the required vaule. 从那里,您应该很容易找出如何访问所需的值。

$data['demo1'][0]['img'];

Creating a helper function for ease of use 创建一个易于使用的助手功能

For ease of use, you can create a helper function to make this process easier. 为了易于使用,您可以创建一个辅助函数来简化此过程。 Whenever you want to view the contents of an array, you can simply call dump_array($array); 每当您要查看数组的内容时,都可以简单地调用dump_array($array); and be done with it. 并完成它。 No more messing around with <pre> tags or print_r() . 不再与<pre>标签或print_r()

Function code: 功能码:

function dump_array($array) {
    echo '<pre>' . print_r($array, TRUE) . '</pre>';
}

Usage example: 用法示例:

$arr = ['foo' => range('a','i'), 'bar' => range(1,9)];
dump_array($arr);

after decoding : 解码后:

echo $data->demo[0]->img;

Basically, a { in JSON leads to a -> (it's an object). 基本上,JSON中的{会导致-> (这是一个对象)。 And a [ to a [] , it's an array. [[] ,它是一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM