基本上我有这个代码场景:
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
,有没有办法检查或循环遍历所有索引,而不是逐个写入我发布了?
答案 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
}
答案 1 :(得分:1)
另一个解决方案是使用array_reduce()来检查条件:
if (array_reduce($_SESSION['player_1_pawn'], function (&$flag, $player) {
$flag &= ($player['currentHealth'] <=0);
return $flag;
}, true));
P.S。数组$ _SESSION ['player_1_pawn']为空时要小心。