开发者

Get key values from multidimensional array

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 t开发者_如何转开发he situation where the array indices are sequential. Multidimensional array - how to get specific values from sub-array

Any ideas?

Brian


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.


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";
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜