开发者

Problem in echo array after json decode in foreach

开发者 https://www.devze.com 2023-04-05 21:49 出处:网络
I have this json encode in one row of the database, and i want echo values name_r and units and price_change together in the foreach , how is it?

I have this json encode in one row of the database, and i want echo values name_r and units and price_change together in the foreach , how is it?

[开发者_开发知识库{
    "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"]
}]

this is my 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
            }
        }

this php code output it is this

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

Why output in line 5 & 6 is Array, how is fix it?


Try:

    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>'; 
            }
        }
    }

EDITED: The elements that we want to recover are arrays, so it is necessary to go in a loop to print...


Maybe you could implode the units and price_change arrays to avoid to more foreach inside the main one.

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
            }
        }

Should try the two methods and see which one is less resource consuming

0

精彩评论

暂无评论...
验证码 换一张
取 消