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
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>";
}
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.