Answer the question
In order to leave comments, you need to log in
How to refer to a multidimensional array given a simple array with indices?
there is an array, maybe another where there are more levels, always different ...:
$arr = array('one' => array(
'two' => array('three' => 'stroka')
)
);
array(
'one',
'two',
'three'
);
Answer the question
In order to leave comments, you need to log in
Quick Solution:
function getElementByPath(array &$arr, array $path) {
$el = $arr[array_shift($path)];
if (count($path) === 0) {
return $el;
}
return getElementByPath($el, $path);
}
$arr = array(
'one' => array(
'two' => array(
'three' => 'stroka'
)
)
);
$path = array(
'one',
'two',
'three'
);
$el = getElementByPath($arr, $path);
var_dump($el); // ---> 'stroka'
// Последний параметр значение, если элемент не найден
function getElementByPath(array &$arr, array $path, $initial = null) {
return array_reduce($path, function (&$res, $key) use (&$initial) {
return is_array($res) && isset($res[$key]) ? $res[$key] : $initial;
}, $arr);
}
Like this:
function getElement(&$array, $path)
{
if (count($path)==0) return $array;
return getElement($array[array_shift($path)], $path);
}
$arr = array(
'one' => array(
'two' => array(
'three' => 'stroka'
)
)
);
$path = array(
'one',
'two',
'three'
);
echo getElement($arr, $path);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question