3

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

3
  • 1
    Have you tried that solution in the other question? Hint: foreach ($array['values] as $contacts) { … } Commented Jul 25, 2011 at 17:33
  • 1
    use foreach instead of for. Alternatively, there is array_keys() which returns all keys from an array. Commented Jul 25, 2011 at 17:34
  • for random depths array see stackoverflow.com/questions/2416100/… Commented Jul 25, 2011 at 17:36

3 Answers 3

3

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.

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

Comments

3

Another hint regarding syntax - if the array in your original example is called $a, then the values you want are here:

$a['values'][556053]['contact_id']

and here:

$a['values'][596945]['contact_id']

So if there's no additional structure in your array, then this loop is probably what you want:

foreach ($a['values'] as $toplevel_id => $record_data) {
    print "for toplevel_id=[$toplevel_id], contact_id=[" . $record_data['contact_id'] . "]\n";
}

Comments

1
foreach($array['values'] as $sub_arr){
    echo $sub_arr['contact_id'];
}

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.