2

I am trying to get 2 newest dates in a date array and arrange them in order. I was ,yet, merely able to arrange them in order :

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

Please give me a suggestion to get 2 newest dates in $data .

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Lá Dối Trá
  • 31
  • 1
  • 1
  • 5

2 Answers2

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);
?>
Rantanen
  • 156
  • 5
1

If you to get the two newest dates, you should sort the data in the reverse order (switch $b and $a in your sortFunction()). Then you could use array_slice() to extract the two first elements:

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

Outputs:

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

If you want to keep your original order, you could use :

$two_last = array_splice($data, -2) ; // get two last elements
Syscall
  • 19,327
  • 10
  • 37
  • 52