更新时间:2023-09-20 18:25:16
我从Kohana借了以下代码.如果键不存在,它将返回多维数组的元素或NULL(或选择的任何默认值).
I borrowed the code below from Kohana. It will return the element of multidimensional array or NULL (or any default value chosen) if the key doesn't exist.
function _arr($arr, $path, $default = NULL)
{
if (!is_array($arr))
return $default;
$cursor = $arr;
$keys = explode('.', $path);
foreach ($keys as $key) {
if (isset($cursor[$key])) {
$cursor = $cursor[$key];
} else {
return $default;
}
}
return $cursor;
}
鉴于上面的输入数组,请使用以下命令访问其元素:
Given the input array above, access its elements with:
echo _arr($arr, 'id'); // 1234
echo _arr($arr, 'city.country.name'); // USA
echo _arr($arr, 'city.name'); // Los Angeles
echo _arr($arr, 'city.zip', 'not set'); // not set