2

Working on a Laravel application whereby I am consuming some data from an API. I get the response as a JSON object and convert to array. It appears as a complex multi-dimensional array (nested arrays). Am trying to loop through it using a nested foreach so as to reach out to the id of each item but I keep failing..

The response is stored in a variable called usmDet

The array response

array:1 [▼
  0 => array:1 [▼
    0 => array:3 [▼
      "id" => "74696"
      "agents" => array:13 [▶]
      "policies" => array:481 [▶]
    ]
    1 => array:3 [▼
      "id" => "1525"
      "agents" => array:8 [▶]
      "policies" => array:357 [▶]
    ]
  ]
  1 => array:1 [▼
    0 => array:3 [▼
      "id" => "73401"
      "agents" => array:1 [ …1]
      "policies" => array:8 [ …8]
    ]
    1 => array:3 [▼
      "id" => "210"
      "agents" => array:13 [ …13]
      "policies" => array:773 [ …773]
    ]
  ]
]

My nested foreach

 foreach($usmDet as $key => $value){
  if(is_array($value)){
    foreach($value as $key => $value){
      echo $key." ".$value."<br>";
    }
  }
  echo "<br>";
}

1 Answer 1

2

The id is part of the array, as you can access it like $value['id']

In the second foreach to prevent confusion you should select a different name for the key and the value.

Try it like this:

foreach($usmDet as $key => $value){
    if(is_array($value)){
        foreach($value as $k => $v){
            echo $v['id'] . "<br>";
        }
    }
}

Result:

74696
1525
73401
210

Php demo

To get all the values for key "id" when multiple nested arrays, you could use array_walk_recursive

$ids = [];
array_walk_recursive($usmDet, function($value, $key) use (&$ids){
    if ($key === "id") {
        $ids[] = $value;
    }
});

print_r($ids);

Php demo

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

9 Comments

It works fine,, thanks alot,, I have checked my code and noticed that the array has gone a depth further (agents is also nested array) which contains some id property in it.. How can I access it ?
@Martin Do you mean like this? 3v4l.org/tc79q You could use array_walk_recursive
I have stored the values in a variable and dd on the browser 3v4l.org/3NpBD and I get boolean true.. My objective is to store them in an array so that I can use them in the view in a foreach loop..
That is because array_walk_recursive returns a boolean.
Okay,, Thanks alot sir,, You really helped me.. Had never worked with multi-dimensional arrays before
|

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.