Reputation: 486
I want to take the all id values in the json format.
{
"1": {
"name": "test",
"followup": {
"1": {
"id": "98",
"followup": {
"1": {
"id": "93",
"followup": {
"1": {
"id": "174"
},
}
}
}
}
}
}
}
I can achieve this by using nested foreach
. But now the 'followup' key is present in 3 but it may came 6,7 so we can't add 6,7 foreach
.
Upvotes: 1
Views: 125
Reputation: 9396
You can use the array_walk_recursive()
for this, like(DEMO):
$ids = array();
$data = json_decode($str, true);
array_walk_recursive($data, function($v, $k) use (&$ids) {
if ($k === 'id') {
$ids[] = $v;
}
});
var_dump($ids);
This basically goes through every index 1 at a time and matches the the keys against the key id
, and if it matches it captures the value.
Upvotes: 4