php 如何检查是否存在多个数组键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13169588/
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
How to check if multiple array keys exists
提问by Ryan
I have a variety of arrays that will either contain
我有各种各样的数组,它们要么包含
story & message
or just
要不就
story
How would I check to see if an array contains both story and message? array_key_exists()only looks for that single key in the array.
我将如何检查数组是否同时包含故事和消息? array_key_exists()只在数组中查找该单个键。
Is there a way to do this?
有没有办法做到这一点?
采纳答案by alex
If you only have 2 keys to check (like in the original question), it's probably easy enough to just call array_key_exists()twice to check if the keys exists.
如果您只有 2 个要检查的键(就像在原始问题中一样),那么只需调用array_key_exists()两次以检查键是否存在就很容易了。
if (array_key_exists("story", $arr) && array_key_exists("message", $arr)) {
// Both keys exist.
}
However this obviously doesn't scale up well to many keys. In that situation a custom function would help.
然而,这显然不能很好地扩展到许多键。在这种情况下,自定义函数会有所帮助。
function array_keys_exists(array $keys, array $arr) {
return !array_diff_key(array_flip($keys), $arr);
}
回答by Erfan
Here is a solution that's scalable, even if you want to check for a large number of keys:
这是一个可扩展的解决方案,即使您想检查大量密钥:
<?php
// The values in this arrays contains the names of the indexes (keys)
// that should exist in the data array
$required = array('key1', 'key2', 'key3');
$data = array(
'key1' => 10,
'key2' => 20,
'key3' => 30,
'key4' => 40,
);
if (count(array_intersect_key(array_flip($required), $data)) === count($required)) {
// All required keys exist!
}
回答by Mark Fox
Surprisingly array_keys_existdoesn't exist?! In the interim that leaves some space to figure out a single line expression for this common task. I'm thinking of a shell script or another small program.
居然array_keys_exist不存在?!在此期间,留出一些空间来为这个常见任务找出单行表达式。我正在考虑一个 shell 脚本或其他小程序。
Note: each of the following solutions use concise […]array declaration syntax available in php 5.4+
注意:以下每个解决方案都使用[…]php 5.4+ 中可用的简洁数组声明语法
array_diff+ array_keys
array_diff+ array_keys
if (0 === count(array_diff(['story', 'message', '…'], array_keys($source)))) {
// all keys found
} else {
// not all
}
(hat tip to Kim Stacks)
(给Kim Stacks 的帽子提示)
This approach is the most brief I've found. array_diff()returns an array of items present in argument 1 notpresent in argument2. Therefore an empty array indicates all keys were found. In php 5.5 you could simplify 0 === count(…)to be simply empty(…).
这种方法是我发现的最简短的方法。array_diff()返回存在于参数 1 中不存在于参数2 中的项目数组。因此,空数组表示找到了所有键。在 php 5.5 中,您可以简化0 === count(…)为简单的empty(…).
array_reduce+ unset
array_reduce+取消设置
if (0 === count(array_reduce(array_keys($source),
function($in, $key){ unset($in[array_search($key, $in)]); return $in; },
['story', 'message', '…'])))
{
// all keys found
} else {
// not all
}
Harder to read, easy to change. array_reduce()uses a callback to iterate over an array to arrive at a value. By feeding the keys we're interested in the $initialvalue of $inand then removing keys found in source we can expect to end with 0 elements if all keys were found.
更难阅读,更容易改变。array_reduce()使用回调来迭代数组以获得一个值。通过提供我们对 的$initial值感兴趣的键$in,然后删除在源中找到的键,如果找到所有键,我们可以期望以 0 元素结束。
The construction is easy to modify since the keys we're interested in fit nicely on the bottom line.
结构很容易修改,因为我们感兴趣的键非常适合底线。
array_filter& in_array
array_filter& in_array
if (2 === count(array_filter(array_keys($source), function($key) {
return in_array($key, ['story', 'message']); }
)))
{
// all keys found
} else {
// not all
}
Simpler to write than the array_reducesolution but slightly tricker to edit. array_filteris also an iterative callback that allows you to create a filtered array by returning true (copy item to new array) or false (don't copy) in the callback. The gotchya is that you must change 2to the number of items you expect.
编写起来比array_reduce解决方案更简单,但编辑起来稍有技巧。array_filter也是一个迭代回调,允许您通过在回调中返回 true(将项目复制到新数组)或 false(不复制)来创建过滤数组。问题是您必须更改2为您期望的项目数量。
This can be made more durable but verge's on preposterous readability:
这可以变得更持久,但接近荒谬的可读性:
$find = ['story', 'message'];
if (count($find) === count(array_filter(array_keys($source), function($key) use ($find) { return in_array($key, $find); })))
{
// all keys found
} else {
// not all
}
回答by Petr Cibulka
It seems to me, that the easiest method by far would be this:
在我看来,到目前为止最简单的方法是:
$required = array('a','b','c','d');
$values = array(
'a' => '1',
'b' => '2'
);
$missing = array_diff_key(array_flip($required), $values);
Prints:
印刷:
Array(
[c] => 2
[d] => 3
)
This also allows to check which keys are missing exactly. This might be useful for error handling.
这也允许检查准确丢失了哪些键。这可能对错误处理很有用。
回答by iautomation
The above solutions are clever, but very slow. A simple foreach loop with isset is more than twice as fast as the array_intersect_keysolution.
上述解决方案很聪明,但速度很慢。带有isset 的简单foreach 循环比array_intersect_key解决方案快两倍多。
function array_keys_exist($keys, $array){
foreach($keys as $key){
if(!array_key_exists($key, $array))return false;
}
return true;
}
(344ms vs 768ms for 1000000 iterations)
(1000000 次迭代为 344 毫秒与 768 毫秒)
回答by Vasily
One more possible solution:
另一种可能的解决方案:
if (!array_diff(['story', 'message'], array_keys($array))) {
// OK: all the keys are in $array
} else {
// FAIL: some keys are not
}
回答by David Dutkovsky
What about this:
那这个呢:
isset($arr['key1'], $arr['key2'])
only return true if both are not null
如果两者都不为空,则仅返回 true
if is null, key is not in array
如果为空,则键不在数组中
回答by Sven
If you have something like this:
如果你有这样的事情:
$stuff = array();
$stuff[0] = array('story' => 'A story', 'message' => 'in a bottle');
$stuff[1] = array('story' => 'Foo');
You could simply count():
你可以简单地count():
foreach ($stuff as $value) {
if (count($value) == 2) {
// story and message
} else {
// only story
}
}
This only works if you know for sure that you ONLY have these array keys, and nothing else.
这仅在您确定只有这些数组键时才有效,而没有其他任何东西。
Using array_key_exists() only supports checking one key at a time, so you will need to check both seperately:
使用 array_key_exists() 仅支持一次检查一个键,因此您需要分别检查两个键:
foreach ($stuff as $value) {
if (array_key_exists('story', $value) && array_key_exists('message', $value) {
// story and message
} else {
// either one or both keys missing
}
}
array_key_exists()returns true if the key is present in the array, but it is a real function and a lot to type. The language construct isset()will almost do the same, except if the tested value is NULL:
array_key_exists()如果键存在于数组中,则返回 true,但它是一个真正的函数,需要输入很多内容。语言结构isset()将几乎相同,除非测试值为 NULL:
foreach ($stuff as $value) {
if (isset($value['story']) && isset($value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
Additionally isset allows to check multiple variables at once:
此外,isset 允许一次检查多个变量:
foreach ($stuff as $value) {
if (isset($value['story'], $value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
Now, to optimize the test for stuff that is set, you'd better use this "if":
现在,为了优化设置的东西的测试,你最好使用这个“if”:
foreach ($stuff as $value) {
if (isset($value['story']) {
if (isset($value['message']) {
// story and message
} else {
// only story
}
} else {
// No story - but message not checked
}
}
回答by Steve
I use something like this quite often
我经常使用这样的东西
$wantedKeys = ['story', 'message'];
$hasWantedKeys = count(array_intersect(array_keys($source), $wantedKeys)) > 0
or to find the values for the wanted keys
或查找所需键的值
$wantedValues = array_intersect_key($source, array_fill_keys($wantedKeys, 1))
回答by Kim Stacks
This is the function I wrote for myself to use within a class.
这是我为自己编写的在类中使用的函数。
<?php
/**
* Check the keys of an array against a list of values. Returns true if all values in the list
is not in the array as a key. Returns false otherwise.
*
* @param $array Associative array with keys and values
* @param $mustHaveKeys Array whose values contain the keys that MUST exist in $array
* @param &$missingKeys Array. Pass by reference. An array of the missing keys in $array as string values.
* @return Boolean. Return true only if all the values in $mustHaveKeys appear in $array as keys.
*/
function checkIfKeysExist($array, $mustHaveKeys, &$missingKeys = array()) {
// extract the keys of $array as an array
$keys = array_keys($array);
// ensure the keys we look for are unique
$mustHaveKeys = array_unique($mustHaveKeys);
// $missingKeys = $mustHaveKeys - $keys
// we expect $missingKeys to be empty if all goes well
$missingKeys = array_diff($mustHaveKeys, $keys);
return empty($missingKeys);
}
$arrayHasStoryAsKey = array('story' => 'some value', 'some other key' => 'some other value');
$arrayHasMessageAsKey = array('message' => 'some value', 'some other key' => 'some other value');
$arrayHasStoryMessageAsKey = array('story' => 'some value', 'message' => 'some value','some other key' => 'some other value');
$arrayHasNone = array('xxx' => 'some value', 'some other key' => 'some other value');
$keys = array('story', 'message');
if (checkIfKeysExist($arrayHasStoryAsKey, $keys)) { // return false
echo "arrayHasStoryAsKey has all the keys<br />";
} else {
echo "arrayHasStoryAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasMessageAsKey, $keys)) { // return false
echo "arrayHasMessageAsKey has all the keys<br />";
} else {
echo "arrayHasMessageAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasStoryMessageAsKey, $keys)) { // return false
echo "arrayHasStoryMessageAsKey has all the keys<br />";
} else {
echo "arrayHasStoryMessageAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasNone, $keys)) { // return false
echo "arrayHasNone has all the keys<br />";
} else {
echo "arrayHasNone does NOT have all the keys<br />";
}
I am assuming you need to check for multiple keys ALL EXIST in an array. If you are looking for a match of at least one key, let me know so I can provide another function.
我假设您需要检查数组中的多个键 ALL EXIST。如果您正在寻找至少一个键的匹配项,请告诉我,以便我提供另一个功能。
Codepad here http://codepad.viper-7.com/AKVPCH

