0

基本上我有这个代码场景:

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']如果 all小于0,是否有任何方法可以检查或遍历所有索引,
而不是像我发布的那样一一编写?

4

2 回答 2

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
}
于 2012-07-22T09:09:07.490 回答
1

另一种解决方案是使用array_reduce()来检查条件:

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

PS 当数组 $_SESSION['player_1_pawn'] 为空时要小心。

于 2012-07-22T09:28:58.940 回答