2017-04-21 81 views
1

我有一個這樣的多維數組。通過多維數組循環並檢查條件

[ 
    0 => array:3 [ 
    "volume" => 1272.0 
    "overflow" => 0 
    "deficit" => 0 
    ] 
    1 => array:3 [ 
    "volume" => 2352.0 
    "overflow" => 0 
    "deficit" => 0 
    ] 
    2 => array:3 [ 
    "volume" => 3144.0 
    "overflow" => 0 
    "deficit" => 0 
    ] 
    3 => array:3 [ 
    "volume" => 6048.0 
    "overflow" => 0 
    "deficit" => 0 
    ] 
    4 => array:3 [ 
    "volume" => 8952.0 
    "overflow" => 0 
    "deficit" => 0 
    ] 
] 

我有$ count變量,當嵌套數組中的overflow和deficit都爲零時,它會增加。爲此,我嘗試以下循環。

$keys = array_keys($waterLevels); 
$count = 0; 
for ($i = 0; $i < count($waterLevels); $i++){ 
    foreach ($waterLevels[$keys[$i]] as $key => $value) 
    { 
     if (($key === 'overflow' and $value == 0) and ($key === 'deficit' and $value == 0)){ 
      $count = $count + 1; 
     } 
    } 
} 

如果我運行這個循環,我應該得到$ count值爲5.我知道'if'條件有問題。如果我單獨嘗試「溢出」,它就會起作用。如果我添加下一個'和'條件,則不會。我在這裏錯過了什麼邏輯?

回答

1

只有這種急需: -

$count = 0; 
foreach ($waterLevels as $value){ 
    if ($value['overflow'] == 0 && $value['deficit'] == 0){ 
     $count = $count + 1; 
    } 
} 
echo $count; 

輸出: - https://eval.in/780558