1

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.

3
  • You need to get the followup id? what must be the desired output of your example? Commented Apr 4, 2018 at 14:14
  • 1
    See array_walk_recusive(). Commented Apr 4, 2018 at 14:15
  • you need to loop through it if you want to access that keys. I think you should try to simplify your json object, so it wouldn't be so nested Commented Apr 4, 2018 at 14:18

1 Answer 1

4

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.

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

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.