S
S
Sasha Brahms2015-11-08 18:55:03
PHP
Sasha Brahms, 2015-11-08 18:55:03

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')
                                          )
                    );

and there is an array (path) to 'stroka', as if the keys of the $arr array:
array(
'one',
'two',
'three'
);

How to apply?
Well, how would it be necessary for the call to be like $arr[one][two][three]
The number of levels can be different, this is the problem...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2015-11-08
@iNikNik

Quick Solution:

function getElementByPath(array &$arr, array $path) {
    $el = $arr[array_shift($path)];
    if (count($path) === 0) {
        return $el;
    }
    return getElementByPath($el, $path);
}

Work example:
$arr = array(
    'one' => array(
        'two' => array(
            'three' => 'stroka'
        )
    )
);

$path = array(
    'one',
    'two',
    'three'
);


$el = getElementByPath($arr, $path);
var_dump($el); // ---> 'stroka'

Add any checks and it will be ok.
// Последний параметр значение, если элемент не найден
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);
}

P
profesor08, 2015-11-08
@profesor08

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 question

Ask a Question

731 491 924 answers to any question