2012-07-22 60 views
0

基本上我有這樣的代碼情景:PHP - 檢查三維數組中所有值的任何更簡短的方法?

if($_SESSION['player_1_pawn'][0]['currentHealth'] <=0 && 
    $_SESSION['player_1_pawn'][1]['currentHealth'] <=0 && 
    $_SESSION['player_1_pawn'][2]['currentHealth'] <=0 && 
    $_SESSION['player_1_pawn'][3]['currentHealth'] <=0 && 
    $_SESSION['player_1_pawn'][4]['currentHealth'] <=0) { 
    //some code here 
} 

有沒有辦法通過各項指標的,寫這一個個像我檢查或循環,如果所有的
['player_1_pawn'][index]['currentHealth']0
代替貼?

回答

3

只寫一個foreach結構,通過所有的數組元素的循環,你需要檢查:

$flag = true; // after the foreach, flag will be true if all pawns have <= 0 health 
foreach ($_SESSION['player_1_pawn'] as $value) 
{ 
    // for each pawn, check the current health 
    if ($value['currentHealth'] > 0) 
    { 
    $flag = false; // one pawn has a positive current health 
    break; // no need to check the rest, according to your code sample! 
    } 
} 

if ($flag === true) // all pawns have 0 or negative health - run code! 
{ 
    // some code here 
} 
+0

感謝您的回覆,我幾乎感到困惑,因爲您的第一個解決方案沒有解決。這個工作正常,非常感謝。 – macford 2012-07-22 09:36:27

1

還有一個解決辦法是使用array_reduce()來檢查條件:

if (array_reduce($_SESSION['player_1_pawn'], function (&$flag, $player) { 
    $flag &= ($player['currentHealth'] <=0); 
    return $flag; 
}, true)); 

附:數組$ _SESSION ['player_1_pawn']爲空時請小心。

+0

哦,是的,錯過了關於使用JQuery,是啊這應該也工作,謝謝 – macford 2012-07-22 09:38:58

相關問題