N
N
Nikolay2018-03-14 12:07:17
PHP
Nikolay, 2018-03-14 12:07:17

How to refer to a multidimensional array using a string?

Hello!
Let's say there is a string cars/bmw
How to access an array $items['cars']['bmw']?
Tried like this:

$getPath = explode('/', $getPath);
$getPath = "['" . implode("']['", $getPath) . "']";
var_dump($items{$getPath});

Swears that there is no such index:
Undefined index: ['cars']['bmw']

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
Lander, 2018-03-14
@iNickolay

$getPath = explode('/', $getPath);
$item = $items;
foreach ($getPath as $key) {
    if (!isset($item[$key])) {
        $item = null;
        break;
    }
 
    $item = $item[$key];
}

var_dump($item);

B
BushaevDenis, 2018-03-14
@BushaevDenis

$getPath = explode('/', $getPath);
$realPath = '';
for ($i = 0; $i < count($getPath) - 1; $i++) {
     $realPath .= $getPath[$i];
}
var_dump($items{$realPath});

A
Alexander Aksentiev, 2018-03-14
@Sanasol

Well, break the string at /
And then climb deep into the array in turn in a normal way.
$items[$key1][$key2][$key3]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question