我想遍历一组条件,仅在满足每个条件时才返回 true,如果不满足则沿途收集原因。<?php$dataval = 0;$tests = [ [1,0,0,4,5], [0,0,0,0,0]];foreach($tests as $condition) { $retval = null; $reasons = []; foreach($condition as $item){ if($item == $dataval){ $retval == $retval && true; } else { $retval == $retval && false; $reasons[] = "Failed to match " . $dataval . " to " . $item; } } if($retval === true){ echo "All conditions met<br>"; } else { echo "NOT all conditions met<br>"; } echo "<pre>" . print_r($reasons, 1) . "</pre>";}?>输出NOT all conditions metArray( [0] => Failed to match 0 to 1 [1] => Failed to match 0 to 4 [2] => Failed to match 0 to 5)NOT all conditions metArray()无论 $retval 的初始值是多少,一个或两个测试都会失败。如果初始值为真,则两个测试都返回真(这是不正确的);如果为 false 或 null,则两者都返回 false(这也是不正确的)。是的,我可以在第一个错误时中断,但是为什么测试失败很重要,并且它可能因不止一个原因而失败,所以我不应该在第一个失败被捕获后立即跳出循环。有没有办法在不添加另一个变量来统计命中和未命中的情况下做到这一点?
1 回答

慕容708150
TA贡献1831条经验 获得超4个赞
您需要初始化$retval为true. 当您遇到不匹配时,将其设置为false并将错误推送到$reason阵列上。
但实际上并不需要$retval变量。只需检查数组是否为空。
foreach($tests as $condition) {
$reasons = [];
foreach($condition as $item){
if($item != $dataval) {
$reasons[] = "Failed to match " . $dataval . " to " . $item;
}
}
if(empty($reasons)){
echo "All conditions met<br>";
} else {
echo "NOT all conditions met<br>";
echo "<pre>" . print_r($reasons, 1) . "</pre>";
}
}
- 1 回答
- 0 关注
- 100 浏览
添加回答
举报
0/150
提交
取消