在foreach中json解码后的echo数组中的问题

时间:2011-09-18 15:36:14

标签: php arrays codeigniter json

我在数据库的一行中有json encode,我想在foreach中一起回显值name_runits以及price_change,它是怎么回事? / p>

[{
    "name_r": "saeed",
    "units": ["salam", "11", "11", "khobe", "22", "22", "salam"],
    "price_change": ["33", "33", "33", "44", "44", "44"]
}, {
    "name_r": "salavat",
    "units": ["55", "55", "khobe", "66", "66"],
    "price_change": ["77", "77", "77", "88", "88", "88", "99", "99", "99"]
}]

这是我的php:

        foreach ($query->result() as $row){
            $data = json_decode($row->residence,true);
            foreach($data as $datum){
            echo $datum['name_r'].'<br>';
            echo $datum['units'].'<br>'; //This is line 5
            echo $datum['price_change'].'<br>'; ///This is line 6
            }
        }

这个PHP代码输出就是这个

saeed
Array //Output line 5
Array //Output line 6
salavat
Array //Output line 5
Array //Output line 6

为什么在第5行和第5行输出6是Array,如何解决?

2 个答案:

答案 0 :(得分:1)

尝试:

    foreach ($query->result() as $row){
        $data = json_decode($row->residence,true);
        foreach($data as $datum){
            echo $datum['name_r'].'<br>';
            foreach($datum['units'] as $d){
                echo "\t".$d.'<br>'; 
            }
            foreach($datum['price_change'] as $d){
                echo "\t\t".$d.'<br>'; 
            }
        }
    }

<强>编辑: 我们想要恢复的元素是数组,因此有必要进入循环打印...

答案 1 :(得分:0)

也许你可以破坏单位和price_change数组,以避免在主要数组内部更多的预测。

foreach ($query->result() as $row){
            $data = json_decode($row->residence,true);
            foreach($data as $datum){
            echo $datum['name_r'].'<br>';
            echo implode(',', $datum['units']).'<br>'; //This is line 5 as string, separated by ','
            echo implode(',', $datum['price_change']).'<br>'; ///This is line 6, same as line 5
            }
        }

应该尝试这两种方法,看看哪种方法消耗的资源较少