使用PHP中的foreach-array显示最接近的发布日期标题

时间:2018-10-16 16:51:03

标签: php arrays foreach

我正在开发游戏发行版,在其中显示即将发行的游戏。我只处理游戏信息和发布日期。

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

➜  ~ blkid /dev/nvme0n1p3
/dev/nvme0n1p3: UUID="2276de2b-9370-4577-90ea-3b0191ebea4e" 
TYPE="crypto_LUKS" PARTUUID="b7a643ce-8bca-418f-a631-b0fc8648432c"

➜  ~ blkid /dev/nvme0n1p3 | sed 's/.*UUID="\(.*\)" .*/\1/'        
2276de2b-9370-4577-90ea-3b0191ebea4e" TYPE="crypto_LUKS

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

我尝试使用此行跳过它们:

$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'
        ],
    ],
];

但是出于某种原因,它似乎并没有跳过它们,只是将它们保留在其中。

当试图显示最接近当前日期的游戏名称时,我也不知道从哪里开始。

我的完整代码:

if (strtotime(date('Y-m-d H:i:s')) > strtotime($title['attributes']['release-date'])) continue;

1 个答案:

答案 0 :(得分:1)

您只需要计算发布日期所需的秒数,如果它是正数,请回显它。

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] 

https://3v4l.org/OMetR

如果您的初始数组未排序,然后又想对其进行排序,则可以将它们添加到键为timeleft的数组中,并使用kso​​rt()对键进行排序。

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);

https://3v4l.org/gbLCs