是否有 PHP 函数检查以确保字段设置在数组中

Is there a PHP function that will check to make sure fields are set in an array

php库是否有任何功能来检查是否所有必填字段都设置在一个数组中?例如:

function required_fields($vals,$required_fields_names){
    for($i = 0; $i < count($required_fields_names); $i++){
        if(!array_key_exists($required_fields_names[$i],$vals)){
            return false
        }
    }
    return true;
}

是否已经有本地人 PHP function/method 这样做了?

NO,没有本地方法。

但您可以改进该代码。

<?php 

function check_keys($keys,$array) {
    foreach ($keys as $key) {
        if(!array_key_exists($key, $array)) {
            return false;
        }
    }
    return true;
}

# Test Zone 

$a = array('a' => 1,
           'b' => 2,
           'c' => 3);

$b = ['a','b','c'];
$c = ['a','b'];
$d = ['a','b','d'];


echo (int) check_keys($b,$a).'</br>'; # 1
echo (int) check_keys($c,$a).'</br>'; # 1
echo (int) check_keys($d,$a).'</br>'; # 0
?>

array_difference 是最接近的内置函数:

function required_fields($vals,$required_fields_names){
    $missing_fields = array_difference($required_fields_names, array_keys($vals));
    return empty($missing_fields);
}