navigate multidimensional array with path in flat array
am 18.10.2007 17:32:41 von Snaggy
I have a big multidimensional array and I need to access it at various
levels. The path is stored in a flat array:
I'm doing it like this:
$path = array("people", "men", "tall")
$my_array = <---- this is the big array!
foreach ($path as $x) {$p .= "[\"".$x."\"]" ;}
$str = "$part = $my_array".$p;
eval($str);
which works but is very ugly, I'd like to do something like
$temp = $my_array[$path];
but it doesn't work of course.
What can I do?
thanks
Re: navigate multidimensional array with path in flat array
am 18.10.2007 17:56:39 von luiheidsgoeroe
On Thu, 18 Oct 2007 17:32:41 +0200, Snaggy wrote:
> I have a big multidimensional array and I need to access it at various=
> levels. The path is stored in a flat array:
>
> I'm doing it like this:
>
> $path =3D array("people", "men", "tall")
>
> $my_array =3D <---- this is the big array!
>
> foreach ($path as $x) {$p .=3D "[\"".$x."\"]" ;}
> $str =3D "$part =3D $my_array".$p;
> eval($str);
>
> which works but is very ugly, I'd like to do something like
>
> $temp =3D $my_array[$path];
>
> but it doesn't work of course.
something like:
function _get_from_array($array,$path){
$cur =3D $array;
while($key =3D array_shift($path)){
if(array_key_exists($cur,$pkey)){
$cur =3D $cur[$key];
} else {
trigger_error('array key doesn\'t exist');
return false;
}
}
return $cur;
}
$temp =3D _get_from_array($array,$path);
-- =
Rik Wasmus