如何用php读取json解码数组?

时间:2011-09-29 15:08:29

标签: php json

我有以下数组,我无法弄清楚如何从中获取任何值,这是数组:

Array
(
    [0] => stdClass Object
        (
            [aure] => test
            [menu] => stdClass Object
                (
                    [pizza] => stdClass Object
                        (
                            [Tomato & Cheese] => stdClass Object
                                (
                                    [small] => 5.50
                                    [large] => 9.75
                                )

                            [onion] => stdClass Object
                                (
                                    [small] => 5.50
                                    [large] => 9.75
                                )

                        )

                    [Special Dinners] => stdClass Object
                        (
                            [Chicken Wings Dinner] => stdClass Object
                                (
                                    [price] => 15.80
                                )

                            [onion] => stdClass Object
                                (
                                    [small] => 5.50
                                    [large] => 9.75
                                )

                        )

                )

        )

)

你能给我一个例子,说明我如何得到一个小番茄&的价格。芝士披萨?

2 个答案:

答案 0 :(得分:4)

$array[0]->menu->pizza->{"Tomato & Cheese"}->small;

我使用了花括号,因为没有它们,我就无法获得“番茄和奶酪”(它们有空格)

这将为您提供所有比萨饼

$pizzas = (array) $array[0]->menu->pizza;
foreach($pizzas as $pizzaname => $choices){
    echo $pizzaname." (small) is for ".$choices->small."<br />";
    echo $pizzaname." (large) is for ".$choices->large."<br />";
}

答案 1 :(得分:1)

如果您的名字不仅仅是字母数字,请考虑将json_decodeassoc参数设置为true,以获取嵌套字典而不是对象。

但是,您仍然可以使用以下语法访问奇怪的成员名称:

echo 'Large t&c: ' . jsonArray[0]->menu->pizza->{'Tomato & Cheese'}->large;