本文介绍了PHP的搜索数组键,并获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道在数组中搜索键并返回其值的最佳方法是什么.类似于array_search,但用于密钥.循环是最好的方法吗?
I was wondering what is the best way to search keys in an array and return it's value. Something like array_search but for keys. Would a loop be the best way?
数组:
Array([20120425] => 409 [20120426] => 610 [20120427] => 277
[20120428] => 114 [20120429] => 32 [20120430] => 304
[20120501] => 828 [20120502] => 803 [20120503] => 276 [20120504] => 162)
我要搜索的值:20120504
Value I am searching for : 20120504
推荐答案
密钥已经是...嗯... 密钥
The key is already the ... ehm ... key
echo $array[20120504];
如果不确定密钥是否存在,请对其进行测试
If you are unsure, if the key exists, test for it
$key = 20120504;
$result = isset($array[$key]) ? $array[$key] : null;
次要添加:
$result = @$array[$key] ?: null;
有人可能会说@
是不好的,但要严肃对待:这更易读和直接,不是吗?
One may argue, that @
is bad, but keep it serious: This is more readable and straight forward, isn't?
更新:使用PHP7,我的上一个示例可以在没有消音器的情况下实现
Update: With PHP7 my previous example is possible without the error-silencer
$result = $array[$key] ?? null;
这篇关于PHP的搜索数组键,并获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!