检查数组键是否存在 [英] Checking if an array key exists
问题描述
我有一个由 json_decode()生成的多维数组. json是动态生成的,这意味着一些密钥将随机出现.
I have a multidimensional array produced by json_decode(). The json is dynamically generated, that means some keys will be present randomly.
我想避免未定义的索引:通知,所以我将对数组的调用封装在这样的函数中:
I would like to avoid Undefined index: notice, so i encapsulated the calls to the array in a function like this:
function exists($value) {
if (isset($value)) {
return $value;
}
}
然后我调用数据:
$something = exists($json_array['foo']['bar']['baz']);
但是我仍然得到未定义索引:baz 的通知.有什么建议吗?
But i still get the Undefined index: baz notice. Any suggestions?
推荐答案
看来您是PHP的新手,所以我给出的答案比平时长一些.
It seems you are new to PHP, so I'll give a bit lengthier answer than normal.
$something = exists($json_array['foo']['bar']['baz']);
这等同于您写的内容:
$baz = $json_array['foo']['bar']['baz'];
$something = exists($baz);
您可能已经注意到,这意味着$json_array['foo']['bar']['baz']
在传递给exists()
之前先经过评估.这是未定义索引的来源.
As you may have noticed, this means that $json_array['foo']['bar']['baz']
is evaluated before it's passed to exists()
. This is where the undefined index is coming from.
正确的习惯用法更像这样:
The correct idiom would be more like this:
$something = NULL;
if (isset($json_array['foo']['bar']['baz'])) {
$something = $json_array['foo']['bar']['baz'];
}
以下内容也与上述几行相同:
The following is also identical to the above lines:
$something = isset($json_array['foo']['bar']['baz'])
? $json_array['foo']['bar']['baz']
: NULL;
这篇关于检查数组键是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!