在不生成PHP通知的情况下访问未知数组元素的最佳方法是什么? [英] What is the best way to access unknown array elements without generating PHP notice?
本文介绍了在不生成PHP通知的情况下访问未知数组元素的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这个数组,
ini_set('display_errors', true);
error_reporting(E_ALL);
$arr = array(
'id' => 1234,
'name' => 'Jack',
'email' => 'jack@example.com',
'city' => array(
'id' => 55,
'name' => 'Los Angeles',
'country' => array(
'id' => 77,
'name' => 'USA',
),
),
);
我可以通过以下方式获取国家/地区名称
I can get the country name with
$name = $arr['city']['country']['name'];
但是,如果国家/地区数组不存在,PHP将生成警告:
But if the country array doesn't exist, PHP will generate warning:
Notice: Undefined index ... on line xxx
我可以先做测试:
if (isset($arr['city']['country']['name'])) {
$name = $arr['city']['country']['name'];
} else {
$name = ''; // or set to default value;
}
但这是低效的.获得$arr['city']['country']['name']
的最佳方法是什么
不会生成PHP通知它是否不存在?
But that is inefficient. What is the best way to get $arr['city']['country']['name']
without generating PHP Notice if it doesn't exist?
推荐答案
我从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
这篇关于在不生成PHP通知的情况下访问未知数组元素的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文