我正在制作一个游戏发布版 block ,我会在其中展示即将发布的游戏。我只处理游戏信息和发布日期。
我的数组看起来像这样(实际数组有更多信息,所以这只是一个副本):
$arr = [
[
'id' => 'UP0006-CUSA08724_00-BATTLEFIELDV0000',
'attributes' => [
'name' => 'Battlefield V [test1]',
'thumbnail-url-base' => 'https://store.playstation.com/store/api/chihiro/00_09_000/container/US/en/999/UP0006-CUSA08724_00-BATTLEFIELDV0000/1539651459000/image'
'release-date' => '2018-12-14T00:00:00Z'
],
],
[
'id' => 'UP0006-CUSA08724_00-BATTLEFIELDV0000',
'attributes' => [
'name' => 'Battlefield V [test2]',
'thumbnail-url-base' => 'https://store.playstation.com/store/api/chihiro/00_09_000/container/US/en/999/UP0006-CUSA08724_00-BATTLEFIELDV0000/1539651459000/image'
'release-date' => '2018-10-14T00:00:00Z'
],
],
[
'id' => 'UP0006-CUSA08724_00-BATTLEFIELDV0000',
'attributes' => [
'name' => 'Battlefield V [test3]',
'thumbnail-url-base' => 'https://store.playstation.com/store/api/chihiro/00_09_000/container/US/en/999/UP0006-CUSA08724_00-BATTLEFIELDV0000/1539651459000/image'
'release-date' => '2019-10-14T00:00:00Z'
],
],
];
我想显示离当前发布日期最近的游戏名称,例如[test1],并跳过已经发布的游戏名称,例如[测试2].
我尝试使用这一行跳过它们:
if (strtotime(date('Y-m-d H:i:s')) > strtotime($title['attributes']['release-date'])) continue;
但出于某种原因,它似乎并没有跳过它们,只是将它们保留在里面。
此外,在尝试显示最接近当前发布日期的游戏名称时,我也不知道从哪里开始。
我的完整代码:
foreach($json['included'] as $key => $title) {
$cusa = substr(explode('-', $title['id'], 3)[1], 0, -3);
if($title['type'] == 'game' && substr($cusa, 0, 4) == 'CUSA') {
// if the day of release has already passed, skip
if (strtotime(date('Y-m-d H:i:s')) > strtotime($title['attributes']['release-date'])) continue;
?>
<div class="game-banner" style="background:url(<?php echo $title['attributes']['thumbnail-url-base']; ?>)">
<h4 class="psplus-game-name"><?php echo $title['attributes']['name']; ?></h4>
</div>
<?php
if($key >= 4) break; // display only 3
}
}
}
最佳答案
您只需要计算发布日期的剩余秒数,如果它是正数则回显它。
foreach($arr as $game){
$timeleft = strtotime($game['attributes']['release-date'])-time();
if($timeleft>0) echo floor($timeleft/86400) ." days left to ".$game['attributes']['name'] ." \n";
}
//58 days left to Battlefield V [test1]
//362 days left to Battlefield V [test3]
如果您的初始数组是未排序的,而您想要排序,您可以将它们添加到一个数组中,键为 timeleft,然后使用 ksort() 对键进行排序。
foreach($arr as $game){
$timeleft = strtotime($game['attributes']['release-date'])-time();
if($timeleft>0) $games[$timeleft] = floor($timeleft/86400) ." days left to ".$game['attributes']['name'] ." \n";
}
ksort($games);
echo implode("", $games);
关于php - 在 PHP 中使用 foreach 数组显示最近的发布日期标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52840407/