如何最简单(最快)检查数组是否包含PHP中的N个特定元素。
与
相似L = rnorm(20) # say this is the original vector
subset = runif(20)<0.3 # some conditions to extract the subset
min = min(L[subset])
ind_min = intersect(which(L == min), seq(L)[subset])[1]
而是
array_key_exists($key, array $array)
答案 0 :(得分:2)
您可以使用array_intersect_key(array $requiredKeys, array $array);
它将返回一个带有匹配键的数组,然后您可以比较所需键数组的长度和函数返回的数组长度以检查是否存在
<?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!
}
答案 1 :(得分:1)
$required = ['foo', 'bar', 'baz'];
if (array_diff_key(array_flip($required), $array)) {
throw new Exception(sprintf('Required keys: %s, got: %s',
join(', ', $required),
join(', ', array_keys($array))));
}
如果array_diff_key
返回除空数组(== false
)之外的任何内容,则表示缺少某些键。您甚至可以存储该差异,并告诉用户/开发人员如果您愿意,请准确地告知错误消息中缺少哪些密钥。