php php搜索数组键并获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10457685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php search array key and get value
提问by Keith Power
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_search 的东西,但用于键。循环会是最好的方法吗?
Array:
大批:
Array([20120425] => 409 [20120426] => 610 [20120427] => 277
[20120428] => 114 [20120429] => 32 [20120430] => 304
[20120501] => 828 [20120502] => 803 [20120503] => 276 [20120504] => 162)
Value I am searching for : 20120504
我正在寻找的值:20120504
回答by KingCrunch
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;
Minor addition:
次要添加:
$result = @$array[$key] ?: null;
One may argue, that @is bad, but keep it serious: This is more readable and straight forward, isn't?
有人可能会争辩说,这@很糟糕,但请认真对待:这更具可读性和直接性,不是吗?
Update: With PHP7 my previous example is possible without the error-silencer
更新:使用 PHP7,我之前的示例可以在没有错误消音器的情况下实现
$result = $array[$key] ?? null;
回答by Fleshgrinder
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
回答by Marc B
array_search('20120504', array_keys($your_array));
回答by Justin P Greer
Here is an example straight from PHP.net
这是一个直接来自 PHP.net 的例子
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "$a[$k] => $v.\n";
}
in the foreach you can do a comparison of each key to something that you are looking for
在 foreach 中,您可以将每个键与您正在寻找的东西进行比较

