php - How do I access values in a multidimensional array dynamically with a variable number of indices? -


essentially, have multidimensional array (it's more extensive bare skeleton need access):

$arr = [     1 => [          'val1' => 'foo',         'val2' => 'bar',     ],     2 => [         'type1' => [             'val3' => 'baz',             'val4' => 'fuz',         ],     ], ] 

i accessing array dynamically , won't know whether i'll accessing $arr[1] or $arr[2] until try so. therefore, don't know how many levels deep need go until time comes. looking function accesses varying number of levels deep of multidimensional array can't find that. know can if or switch statement i'm trying simplify like:

if ( isset( $arr[$var]...... ) ) {     return $arr[$var]......; } 

my problem can't figure out how build string replace "......" proper number of indices. tried making string using loop:

function getaccessstring( array $arrofindices ) {     $str = '';     foreach( $arrofindices $index ) {         $str .= '['.$index.']';     }     return $str; } 

however, couldn't variation of string-making function work in sense concatenate in way access multidimensional array.

p.s. if there no way access array in simple format along line of this...

if ( isset( $arr[$var]...... ) ) {     return $arr[$var]......; } 

... use switch statement. using iterators, parsing array , whatnot not going simpler switch statement i've got.

function getarrayelement($arr, $arrayofindices) {     $result = $arr;     foreach ($arrayofindices $index) {         $result = $result[$index];     }     return $result; }  $arr = [     1 => [          'val1' => 'foo',         'val2' => 'bar',     ],     2 => [         'type1' => [             'val3' => 'baz',             'val4' => 'fuz',         ],     ], ]; echo getarrayelement($arr, [1, 'val1']); // echoes foo echo getarrayelement($arr, [2, 'type1', 'val4']); // echoes fuz 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -