我循环浏览两个阵列(健身房和游戏)并将$ gym [' id']值与$ game [' gym_id']进行比较。如果两个值匹配,我会显示游戏日期和时间,如下所示。
<?php
$gyms = sw::shared()->gyms->getAll();
$games = sw::shared()->games->getAll();
?>
<?php foreach ($gyms as $gym) { ?>
<?php foreach ($games as $game) { ?>
<?php if ($game['gym_id'] == $gym['id']) { ?>
<?php $match++; ?>
<?php echo $gym['gym_name']; ?><br>
<?php echo $game['date']; ?> <?php echo $game['time']; ?><br>
<?php } ?>
<?php } ?>
<?php } ?>
我还用健身房[&#39; gym_name&#39;]显示健身房名称,但我只想要健身房名称显示ONCE,如果健身房有游戏,意味着它看起来像这样:
GYM 1 NAME
GAME 1 DATE GAME 1 TIME
GAME 2 DATE GAME 2 TIME
GAME 3 DATE GAME 3 TIME
GYM 2 NAME
GAME 4 DATE GAME 4 TIME
GAME 5 DATE GAME 5 TIME
GAME 6 DATE GAME 6 TIME
我该如何重写?
答案 0 :(得分:1)
尝试这样的事情。
<?php
$gyms = sw::shared()->gyms->getAll();
$games = sw::shared()->games->getAll();
function getGymGames($gym){
$gymGames = array();
foreach ($games as $game) {
if ($game['gym_id'] == $gym['id']) {
array_push($gymGames,$game);
}
}
return $gymGames;
}
?>
<?php
foreach ($gyms as $gym) {
$gymGames = getGymGames($gym);
if(count($gymGames) > 0){?>
<?=$gym['gym_name'];?><br />
<?foreach($gymGames as $game){
$match++;
?>
<?= $game['date']; ?><br />
<?= $game['time']; ?><br>
<?}
}
}
?>
答案 1 :(得分:1)
我对PHP并不完全熟悉,但为什么不用boolean来标记它是否已经显示,并在显示后切换它。
<?php
$gyms = sw::shared()->gyms->getAll();
$games = sw::shared()->games->getAll();
?>
<?php foreach ($gyms as $gym) { ?>
<?php $notDisplayed=true; ?>
<?php foreach ($games as $game) { ?>
<?php if ($game['gym_id'] == $gym['id']) { ?>
<?php $match++; ?>
<?php if($displayed) { ?>
<?php echo $gym['gym_name']; ?><br>
<?php $notDisplayed=false;?>
<?php } ?>
<?php echo $game['date']; ?> <?php echo $game['time']; ?><br>
<?php } ?>
<?php } ?>