Access multidimensional array by string with delimiter
suppose i have a multidimensional array like something like this:
<?php
$array = array("test1" => array("test2" => array("test3" => 1)), ... foo1 = array("foo2" => 2));
?>
i want to access an array element by passing a string like "test1.test2.test3开发者_开发知识库"
to a function which in turn calls the array element. I could use eval()
by replacing the string with []
(calling $array["test2]["test3"]
...) but i wonder if there is a different more solid approach in calling a array element without traversing through all of its depth or use eval()
.
You could use
function get_multi($arr, $str) {
foreach (explode('.', $str) as $key) {
if (!array_key_exists($key, $arr)) {
return NULL;
}
$arr = $arr[$key];
}
return $arr;
}
Symfony provides a PropertyAccess component for this.
The PropertyAccess component provides function to read and write from/to an object or array using a simple string notation.
精彩评论