2017-04-20 58 views
0

我有這樣一個循環:PHP計算價值在每個循環迭代多少次已存在

foreach ($result_new as $count){ 
echo "<pre>"; print_r($count); 
} 

這是生產什麼:

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 
        ) 

      ) 

    ) 

) 

我需要什麼找在每次迭代中出現「ADDRESS CHECK FAILED」(地址檢查失敗)多少次,然後進行比較。我試過這個:

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"; 
} 

問題是,$地址值繼續增加與每個循環,但我只是想循環當前總計。

+1

「問題在於,每個循環的$地址值都會繼續增加,但我只希望循環總數。」我假設你的意思是你想計算每個$ count數組中出現的總數是否正確?如果是這樣的話,這裏定義的in_array_r函數:https://gist.github.com/Billy-/bc6865066981e80e097f不會因爲它返回一個布爾值而削減它。您應該修改它以返回計數。 – clarkatron

+0

@clarkatron但我想要的是統計有多少次是真實的,但不是針對整個循環僅針對當前,然後重新開始......這是否合理? –

回答

1

剛需在foreach循環結束時重置$地址值,所以每次都會對當前元素值進行計數而不是整個循環

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; 
} 
0

如果我理解正確的問題,我認爲你需要做這樣的事情:

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; 
} 

然後,您可以使用它像這樣:

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"; 
    } 
} 
相關問題