在foreach循环中json解码数组

时间:2015-02-17 23:33:45

标签: php json

我无法从json_decoded数组中打印值。

<?php

class calculate {

    public function random_stuff()
    {
        $users_array = array(
            'attributes'  => array(
                'age'       => '25', 
                'height'    => '1.75cm', 
                'weight'    => '70kg'
            ),
            'savings'     => array(
                'cash'      => 3000,
                'bank'      => rand(1, 222)
            )
        );

        $users_array = json_encode($users_array);
        $value       = json_decode($users_array, true);
        return $value;
    }

}

$calculate = new calculate;
$arr = $calculate->random_stuff();
foreach($arr['attributes'] as $row)
{
    echo '<br />' . $row['height'];
}

?>

我得到的只是: 警告:非法字符串偏移&#39;高度&#39;在第30行的/Applications/MAMP/htdocs/index.php

2 警告:非法字符串偏移&#39;高度&#39;在第30行的/Applications/MAMP/htdocs/index.php

1 警告:非法字符串偏移&#39;高度&#39;在第30行的/Applications/MAMP/htdocs/index.php

7

我做错了什么?我已经检查了一些类似的堆栈主题,看起来我正在以正确的方式做这件事吗?

3 个答案:

答案 0 :(得分:1)

您正在使用foreach($arr['attributes'] as $row)

迭代此数组
        array(
            'age'       => '25', 
            'height'    => '1.75cm', 
            'weight'    => '70kg'
        ),

所以在第一次迭代中,$ row是字符串'25'

应用于字符串的方括号表示您要从数字偏移量中提取字符,但$row['height']显然不是有效的偏移量,并且您得到错误。

如果你只想要身高,那就是这样的

$arr = $calculate->random_stuff();
echo '<br />' . $arr['attributes']['height'];

最后,当你遇到这样的问题时,一个简单的方法就是在各个点上var_dump()个变量来检查你的假设是否有效。

答案 1 :(得分:0)

消息显示您正在尝试访问未定义的数组的键。

这是因为如果循环$ arr ['attributes'],你将获得在属性中定义的所有密钥对。 要更好地理解它,请尝试print_r($ arr ['attributes']或者甚至更好地尝试在没有['height']的情况下回显$ row。

答案 2 :(得分:0)

您正在迭代一个对象,而不是一个数组。当你这样做时:

foreach($arr['attributes'] as $row)
{
    echo '<br />' . $row['height'];
}

$row是&#39; 25&#39;然后&#39; 1.75厘米&#39;最后&#39; 70kg&#39;。如果你想进入&#34;身高&#34;这样做

print($arr["attributes"]["height"]);

如果要迭代所有属性

foreach($arr['attributes'] as $name => $value)
{
    print("attribute $name = $value <br>");
}
相关问题