Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key values from multidimensional array

Tags:

arrays

php

I have a page that searches a database and generates the following array. I'd like to be able to loop through the array and pick out the value next assigned to the key "contact_id" and do something with it, but I have no idea how to get down to that level of the array.

The array is dynamically generated, so depending on what I search for the index numbers under "values" will change accordingly.

I'm thinking I have to do a foreach starting under values, but I don't know how to start a foreach at a sublevel of an array.

Array ( 
[is_error] => 0 
[version] => 3 
[count] => 2 
[values] => Array ( 
    [556053] => Array ( 
        [contact_id] => 556053 
        [contact_type] => Individual 
        [first_name] => Brian 
        [last_name] => YYY 
        [contact_is_deleted] => 0 
    ) 
    [596945] => Array ( 
        [contact_id] => 596945 
        [contact_type] => Individual 
        [first_name] => Brian 
        [last_name] => XXX 
        [contact_is_deleted] => 0 
    ) 
) 

)

I've looked at the following post, but it seems to only address the situation where the array indices are sequential. Multidimensional array - how to get specific values from sub-array

Any ideas?

Brian

like image 963
bpmccain Avatar asked Aug 05 '26 23:08

bpmccain


1 Answers

You are correct in your assumption. You could do something like this:

foreach($array['values'] as $key => $values) {
  print $values['contact_id'];
}

That should demonstrate starting at a sub level. I would also add in your checks to see if its empty and if its an array... etc.

like image 189
iLLin Avatar answered Aug 08 '26 13:08

iLLin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!