0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

You should also explain why it's happening.
@Alfonso Rubalcava - Thanks, did there is not way except foreach?
Jenifer: There are several ways to do... While, ArrayIterator... foreach is simple ;)
If you do not need to interact with the data, @CoBaLt2760 option works too.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.