0

Hello guys just need a little help here. Because I have a json data and I decode it. But I can't access it using the foreach loop. When I tried to print the array structure I got this:

Array
(
    [0] => stdClass Object
        (
            [code] => AD
            [country] => Andorra
        )

    [1] => stdClass Object
        (
            [code] => AE
            [country] => United Arab Emirates
        )

    [2] => stdClass Object
        (
            [code] => AF
            [country] => Afghanistan
        )

    [3] => stdClass Object
        (
            [code] => AG
            [country] => Antigua and Barbuda
        )

    .
    .
    .

All I want is to access the code and country

I used this loop but it display the index name and the values:

foreach($decode_country as $p){
   foreach($p as $key => $value){
      echo $key."--".$value."<br />";
   }
}

But it display:

code--AD
country--Andorra
code--AE
country--United Arab Emirates
code--AF
country--Afghanistan
code--AG
country--Antigua and Barbuda
code--AI
country--Anguilla
code--AL
country--Albania
code--AM
country--Armenia

2 Answers 2

2

Try like

foreach($decode_country as $p){
   echo "code -- ".$p->code."<br>";
   echo "country -- ".$p->country."<br>";
}

Here $p will be considered as an object and you can extract the code and country using $p->code and $p->country.Or Better : while decoding json data you need to give like

$decode_country = json_decode($data,true);

true will return the array result.Then use

foreach($decode_country as $p){
   echo "code -- ".$p['code']."<br>";
   echo "country -- ".$p['country']."<br>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

I also included the boolean TRUE in my decoding but same effect. I got Trying to get property of non-object
1

You may try this

foreach($decode_country as $p){
    echo $p->code;
    echo $p->country;
}

Here $decode_country is an array of objects and inside foreach loop, each $p is an object.

If you use json_decode($data, true); then use

echo $p['code'];

When TRUE is used, returned objects will be converted into associative arrays. Otherwise, use

echo $p->code;

7 Comments

That's weired, var_dump($decode_country[0]) should print first object in the array, try this.
When I var_dump it. It results to: array(2) { ["code"]=> string(2) "AD" ["country"]=> string(7) "Andorra" }
Can you show more code with json_decode ? Use json_decode($data); because you are using object notation.
You mean the json result before decoding it?
Ok I got an answer from Gautam3164. Thanks for the suggestions. :)
|

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.