编辑:
您的问题已更新两次。 如果其中一个值未填充,您可能想将$bank视为“空” –我的原始答案(以下)仅在所有值均与函数匹配时才返回true 。 我们需要容纳的是一个稍微不同的函数array_some 。
function array_some(callable $f, array $xs) {
foreach (array_values($xs) as $x)
if (call_user_func($f, $x))
return true;
return false;
}
$input = [
[
'bank_name' => [],
'bank_code' => null,
'branch' => null,
'account_number' => null,
'accout_type' => null
],
[
'bank_name' => ['foobar'],
'bank_code' => 123,
'branch' => null,
'account_number' => null,
'accout_type' => null
],
[
'bank_name' => 'Bank Name',
'bank_code' => 7083,
'branch' => 'Branch Name',
'account_number' => '234234324242',
'accout_type' => 'NRFC'
]
];
function is_empty($x) { return empty($x); }
foreach ($input as $bank) {
$proceed = array_some('is_empty', $bank);
echo 'proceed:', json_encode($proceed), PHP_EOL;
}
// proceed:true
// proceed:true
// proceed:false
在第一个示例中, 某些字段为空,因此$proceed将为true
在第二个示例中, 某些字段为空,因此$proceed将为true
在第三个示例中, 所有字段均为非空 ,因此$proceed将为false
原始答案:
您正在寻找的是一个array_every函数。 让我们从一个简单的例子开始:
function array_every(callable $f, array $xs) {
foreach (array_values($xs) as $x)
if (!call_user_func($f, $x))
return false;
return true;
}
function even($x) { return $x % 2 === 0; }
echo "even:", json_encode(array_every('even', [1,2,3])), PHP_EOL; // false
echo "even:", json_encode(array_every('even', [2,4,6])), PHP_EOL; // true
在第一示例中, 1 , 2 ,和3 不都是 even ,所以输出是假的 。
在第二示例中, 2 , 4 ,和6 都是 even ,所以输出是真实的 。
现在用您的数据来看一下
function array_every(callable $f, array $xs) {
foreach (array_values($xs) as $x)
if (!call_user_func($f, $x))
return false;
return true;
}
$input = [
[
'bank_name' => [],
'bank_code' => null,
'branch' => null,
'account_number' => null,
'accout_type' => null
],
[
'bank_name' => ['foobar'],
'bank_code' => 123,
'branch' => null,
'account_number' => null,
'accout_type' => null
]
];
function is_empty($x) { return empty($x); }
foreach ($input as $bank) {
$proceed = array_every('is_empty', $bank);
echo 'proceed:', json_encode($proceed), PHP_EOL;
}
// proceed:true
// proceed:false
在第一个示例数据中, 所有数组值均为empty ,因此$proceed将为true 。
在第二个示例中, 某些值是(非empty ),因此$proceed将为false 。
注意:因为empty 是语言构造而不是函数 ,所以不能使用变量函数来调用它。 –这就是为什么我定义了一个可重用的is_empty函数而不是使用array_every('empty', ...) -这将不起作用。