从阵列中选择2个最新日期并按顺序排列

时间:2018-03-22 15:18:28

标签: php arrays sorting datetime

我正在尝试在日期数组中获取2个最新日期并按顺序排列它们。然而,我只是能够按顺序排列它们:

<?php
$data = array(
    array(
        "title" => "Another title",
        "date"  => "Fri, 17 Jun 2011 08:55:57 +0200"
    ),
    array(
        "title" => "Another title",
        "date"  => "Fri, 17 Jun 2014 08:55:57 +0200"
    ),
    array(
        "title" => "My title",
        "date"  => "Mon, 18 Jun 2012 09:55:57 +0200"
    )
);

function sortFunction( $a, $b ) {
    return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);
?>

请给我一个建议,以便在$ data中获得2个最新日期。

2 个答案:

答案 0 :(得分:1)

<?php
$data = array(
    array(
        "title" => "Title 1",
        "date"  => "Fri, 17 Jun 2011 08:55:57 +0200"
    ),
    array(
        "title" => "Title 2",
        "date"  => "Sat, 18 Jun 2011 09:55:57 +0200"
    ),
      array(
        "title" => "Title 3",
        "date"  => "Sun, 19 Jun 2011 08:55:57 +0200"
    ),
      array(
        "title" => "Title 4",
        "date"  => "Mon, 20 Jun 2011 08:55:57 +0200"
    )
);

//Sort them DESC by date. (switch $a for $b AND $b for $a)
function sortFunction( $a, $b ) {
    return strtotime($b["date"]) - strtotime($a["date"]);
}
usort($data, "sortFunction");


//Number of dates you want to display
$datesToDisplay = 2;
//An array to push in our desired number of dates
$dates = [];

for($i = 0; $i < $datesToDisplay; $i++){
    array_push($dates, $data[$i]);
}


print_r($dates);
?>

答案 1 :(得分:1)

如果要获取两个最新日期,则应按相反顺序对数据进行排序(在$b中切换$asortFunction()。然后你可以使用offical link来提取两个第一个元素:

function sortFunction($a, $b) {
    // switch $b and $a:
    return strtotime($b["date"]) - strtotime($a["date"]);
}
// sort data from newest to oldest
usort($data, "sortFunction");

// extract two first elements:
$two_first = array_splice($data, 0, 2) ;

print_r($two_first);

输出:

Array (
    [0] => Array (
            [title] => Another title
            [date] => Fri, 17 Jun 2014 08:55:57 +0200
        )
    [1] => Array (
            [title] => My title
            [date] => Mon, 18 Jun 2012 09:55:57 +0200
        )
)

如果您想保留原始订单,可以使用:

$two_last = array_splice($data, -2) ; // get two last elements