我有两个数组:$values
和$availableKeys
。如果$values
包含不允许的密钥,我想抛出异常。目前我正在运行此代码。
foreach ($values as $key => $value) {
if (!in_array($key, $availableKeys)) {
throw new RuntimeException(
'Not allowed key'
);
}
}
存在更好的验证阵列的方法吗?问题Validate PHP Array Key>Value没有回答我的问题。
答案 0 :(得分:1)
if (array_diff_key($values, array_flip($availableKeys))) {
throw new RuntimeException(..);
}
答案 1 :(得分:0)
我只能说测试,该键存在于数组中,更快。所以make array $ availableKeys不是[key1,key2 ...]但是[key1 => 1,key2 => 1 ...]。即,翻转你当前的数组
foreach ($values as $key => $value) {
if (!isset($availableKeys[$key])) {
throw new RuntimeException(
'Not allowed key'
);
}
}
答案 2 :(得分:0)
您可以使用array_diff()搜索不允许的密钥:
$allowedKeys = array("a","b","c");
$test = array("a" => "asdf", "c" => "asdf", "d" => "asdf");
$notAllowedKeys = array_diff(array_keys($test), $allowedKeys);
if($notAllowedKeys) {
print "One or more keys are not allowed";
print_r($notAllowedKeys);
}