检查数组中不允许的键?

Check for unallowed keys in an array?

检查数组是否包含不允许的键的最佳方法是什么?

$array = array("Apple" => 33, "Orange" => 22, "Dogs" => 77,);

$allowed = array("Apple", "Orange");

期望的输出是:

if (!something($array,$allowed)){echo 'Unallowed data';}

谢谢

使用array_intersect_key()

var_dump(array_intersect_key($array, array_flip($allowed)));

您可以使用 array_diff() 查找不允许的密钥:

$keys = array_keys($array);
$notAllowed = array_diff($keys, $allowed);
var_dump($notAllowed); // "Dogs"

这是一个执行此操作的函数:

function something($array, $keys) {
    return ! array_diff(array_keys($array), $keys);
}
// Usage...
if ( ! something($array, $allowed)) {
    echo 'Unallowed data';
}

如果您可以为允许的值使用关联(映射)数组,那么您可以在 O(1) 中对允许的键执行搜索。使用您当前的数据结构,搜索允许的地图将花费 O(n) 时间。

$array = array("Apple" => 33, "Orange" => 22, "Dogs" => 77,);

$allowed = array("Apple" => 0, "Orange" => 1);

$found_not_allowed = 0;

foreach($array as $key => $value)
    if(!isset($allowed[$key]))
        $found_not_allowed++;

if($found_not_allowed > 0) 
    echo "Keys were found that are not allowed.";

使用array_diff_key

$array = array("Apple" => 33, "Orange" => 22, "Dogs" => 77,);
$allowed = array("Apple", "Orange");
$allowed = array_flip($allowed);

$res = array_diff_key($array, $allowed);

print_r($res);

echo $allowedTxt = empty($res) ? "Allowed keys only" : "Not allowed keys";

$res 包含不允许的数据。

假设不允许的键是“Dogs