PHP json_decode如何输出数组 [英] php json_decode how to output array

查看:634
本文介绍了PHP json_decode如何输出数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的json格式字符串的php代码:

Here is my php code with json formatted string:

<?php

$string='{"items":  [
    {
    "address":"W 7th Ave"
    },
    {
    "address":"W 8th St"
    }
    ]}'; 

$json = json_decode($string, true);

    foreach ($json as $key => $value){
        echo "$key: $value\n";
    };

?>

我想学习如何将json字符串解析/输出为可以在html中显示或放入数据库的内容..但是我被困在一个很简单的问题上,但是我花了大部分时间试图弄清楚

I want to learn how to parse/output json string into something I can show in html or put into database .. however i am stuck on something that is prob very simple but I've spent most of the morning trying to figure out.

我想理解的是为什么上面代码的结果给我以下结果:

What I want to understand is why the results of my code above gives me the following result:

"items: Array"

不是我想要/期望得到的:

And not what I want/expect to get:

"items: W 7th Ave"
"items: W 8th St"

我想念什么?数组中的项目"下的地址"不是下一个级别"吗?

What am i missing? Isn't "Address" the next "level" down from "Item" in the array?

推荐答案

$string = file_get_contents('./string.json');
$json = json_decode($string);

如果您想拥有items: <address>:

foreach ($json['items'] as $address)
{
    echo "items:". $address['address'] ."\n";
};

无论如何,如果不确定如何构建数组,可以通过以下方式打印它:

anyway if you are not sure about how an array is built you could print it via:

print_r($json);

将打印:

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [address] => W 7th Ave
                )

            [1] => Array
                (
                    [address] => W 8th St
                )
        )
)

现在您发现$json仅包含两个数组的一个数组(items),然后,如果对其进行循环,您将获得在示例中打印的该数组. 如上所述,您需要通过循环items数组中的元素并打印其address元素来更进一步.

now you found out that $json contains just an array (items) of two array, then, if you loop it, you will get that array which is printed in your example. As explained above you need to go one step deeper by looping the elements in your items array and print their address element.

这是完整的脚本: http://pastie.org/2275879

这篇关于PHP json_decode如何输出数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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