Reputation: 39
Been trying all day to do what would appear to be something quite simple and I'm failing to get all children nodes from json (only got the first child within this code):
foreach($obj->data[0]->region as $code_id) {
echo $code_id->code_id . "\n";
}
JSON snippet below:
{
"data": [
{
"record_id": 9,
"region": [
{
"code_id": 2,
"code_name": "CA"
},
{
"code_id": 3,
"code_name": "WY"
}
]
},
{
"record_id": 10,
"region": [
{
"code_id": 4,
"code_name": "CA"
},
{
"code_id": 5,
"code_name": "WY"
}
]
}
]
}
Any link or suggestion for tutorial really appreciate :(
Upvotes: 0
Views: 171
Reputation: 55427
If you want to loop over both arrays, the following will work:
// Loop over everything inside of data
foreach($obj->data as $thing ) {
// Loop over each region
foreach($thing->region as $region) {
echo $region->code_id . "\n";
}
}
The output is:
2
3
4
5
Demo here: https://3v4l.org/NQTV6
Upvotes: 1
Reputation: 1523
try this...
Not the most optimised solution but should get you back on track.
foreach($obj->data[0] as $record) {
if(isset($record->region)){
foreach($record->region as $code){
echo $code->code_id . "\n";
}
}
}
Upvotes: 0