Answer the question
In order to leave comments, you need to log in
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});
Undefined index: ['cars']['bmw']
Answer the question
In order to leave comments, you need to log in
$getPath = explode('/', $getPath);
$item = $items;
foreach ($getPath as $key) {
if (!isset($item[$key])) {
$item = null;
break;
}
$item = $item[$key];
}
var_dump($item);
$getPath = explode('/', $getPath);
$realPath = '';
for ($i = 0; $i < count($getPath) - 1; $i++) {
$realPath .= $getPath[$i];
}
var_dump($items{$realPath});
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 questionAsk a Question
731 491 924 answers to any question