[英]PHP Count How Many Times a Value Exists in Each Iteration of a Loop
I have a loop like this: 我有这样一个循环:
foreach ($result_new as $count){
echo "<pre>"; print_r($count);
}
This is what is produced: 这是产生的:
Array
(
[0] => Array
(
[0] => TomVanhecker
[1] => PASS
[2] => Array
(
[0] => Array
(
)
)
)
)
Array
(
[0] => Array
(
[0] => DonLay
[1] => PASS
[2] => Array
(
[0] => Array
(
[0] => ADDRESS CHECK FAILED
)
)
)
)
Array
(
[0] => Array
(
[0] => PetraBerumen
[1] => REVIEW
[2] => Array
(
[0] => Array
(
[0] => ADDRESS CHECK FAILED
)
)
)
[1] => Array
(
[0] => PetraBerumen
[1] => REVIEW
[2] => Array
(
[0] => Array
(
[0] => ADDRESS CHECK FAILED
)
)
)
[2] => Array
(
[0] => PetraBerumen
[1] => REVIEW
[2] => Array
(
[0] => Array
(
[0] => ADDRESS CHECK FAILED
)
)
)
)
What I need it to find out how many times "ADDRESS CHECK FAILED" appears in each iteration and then do a comparison. 我需要它找出“ ADDRESS CHECK FAILED”在每次迭代中出现多少次,然后进行比较。 I have tried this:
我已经试过了:
foreach ($result_new as $count){
if ((in_array_r("ADDRESS CHECK FAILED", $count)) ){
$address++
}
if($address > 2){
echo "There was more than two address failures for this customer";
}
The problem is that the $address value continues to increment with each loop but I just want that loops current total. 问题是$ address值在每个循环中都继续增加,但是我只希望循环当前总数。
Just need to reset $address value at the end of the foreach loop, so every time it will count the current element values instead of the entire loop 只需要在foreach循环结束时重置$ address值,因此每次它将计算当前元素值而不是整个循环
foreach ($result_new as $count){
if ((in_array_r("ADDRESS CHECK FAILED", $count)) ){
$address++;
}
if($address > 2){
echo "There was more than two address failures for this customer";
}
$address = 0;
}
If I'm understanding the problem correctly, I think you need to do something like this: 如果我正确理解了问题,我认为您需要执行以下操作:
function in_array_recursive_count($needle, $haystack, &$current = 0, $strict = false) {
foreach ($haystack as $item) {
if ($strict ? $item === $needle : $item == $needle) {
$current++;
}
else if(is_array($haystack)) {
in_array_recursive_count($needle, $haystack, $current, $strict);
}
}
return $current;
}
Then, you'd use it like so: 然后,您将像这样使用它:
foreach ($result_new as $count){
$address = in_array_recursive_count("ADDRESS CHECK FAILED", $count);
if($address > 2){
echo "There was more than two address failures for this customer";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.