在PHP中使用foreach数组显示最近的发布日期标题

在PHP中使用foreach数组显示最近的发布日期标题,php,arrays,foreach,Php,Arrays,Foreach,我正在做一个游戏发布部分,在那里我展示即将发布的游戏。我只处理游戏信息和发布日期 我的阵列看起来像这样(实际阵列有更多信息,所以这只是一个复制): 我想显示最接近当前发布日期的游戏标题,如[test1],并跳过已经发布的游戏标题,如[test2] 我试着用这句话跳过它们: if (strtotime(date('Y-m-d H:i:s')) > strtotime($title['attributes']['release-date'])) continue; 但出于某种原因,它似乎并没

我正在做一个游戏发布部分,在那里我展示即将发布的游戏。我只处理游戏信息和发布日期

我的阵列看起来像这样(实际阵列有更多信息,所以这只是一个复制):

我想显示最接近当前发布日期的游戏标题,如[test1],并跳过已经发布的游戏标题,如[test2]

我试着用这句话跳过它们:

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($json['include']as$key=>$title){
$cusa=substr(分解('-',$title['id'],3)[1],0,-3);
如果($title['type']='game'&&substr($cusa,0,4)='cusa'){
//如果发布日期已过,请跳过
如果(strotime(date('Y-m-dh:i:s'))>strotime($title['attributes']['release-date'])继续;
?>

您只需要计算发布日期的剩余秒数,如果是正数,则返回它

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] 

如果初始数组未排序,然后需要排序,则可以将它们添加到一个数组中,其中key为timeleft,并使用ksort()对key进行排序


您的问题可能是时区。数据中的时间字符串是UTC。如果PHP的默认时区不是UTC,那么
date('Y-m-d H:i:s')
将为您提供本地时区,并且比较无法正常工作。有很多不同的方法可以实现这一点,最简单的方法可能是使用
gmdate()
而不是
date()
。您还可以考虑使用
DateTime
对象,而不是
strotime()
返回的int,因为可以直接比较
DateTime
对象。嗯,这一点很好。请尝试一下,让您知道@AlexHowansky“似乎没有跳过”是一个非常糟糕的错误描述。请检查,它给出了如何将问题简化为其本质的说明。@UlrichEckhardt不同意。我相信这个问题已经具备了它所需要的一切。(几乎)格式正确的数组、清晰的预期输出和格式正确的代码。您缺少的是什么?
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] 
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);