开发者

Reference array keys without knowing their names?

If I have an array like this:

$array = array('something'=>array('more'=>array('id'=> 34)));

Then print_r($array['something']['more']['id'] works fin开发者_Go百科e.

But say the key names might change but the structure wont. How could I reference the same values without knowing the names?

I thought maybe print_r($array[0][1][2] might work, but of course those keys don't exist.


You can use a foreach statement. Use a recursive function to handle nested arrays (untested):

public function iterateNestedArray($array) {
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            print_r(iterateNestedArray($value));
        }
    }
    else {
        return $array;
    }
}

You might consider implementing this function with a second argument to pass a callback function, rather than just print_ring every value.


There are multiple possibilities.

You could use arrayiterator or simply foreach. Perhaps even array_values could be your solution.


you can do a straight loop with foreach, although it's fairly ugly:

foreach ( $grandparent as $gpkey => $parent ) {
    foreach ( $parent as $pkey => $child ) {
        foreach ( $child as $ckey => $value ) {
            print $gpkey . " - " . $pkey . " - " . $ckey . " = " . $value;
        }
    }
}

Or you can get the list of keys with array_keys():

$keys = array_keys($array);
for ( $i=0, $imax=count($keys); $i<$imax; $i++ ) {
    print $key . " = " . $array[$key];
}


You can use reset(), next() and end() as always

$array = array('something'=>array('more'=>array('id'=> 34)));
echo reset(reset(reset($array)));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜