Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP order array by date? [duplicate]

Possible Duplicate:
PHP Sort a multidimensional array by element containing date

I have some data from XML or JSON in a PHP array that looks like this:

[0]= array(2) {     ["title"]= string(38) "Another title"     ["date"]= string(31) "Fri, 17 Jun 2011 08:55:57 +0200" } [1]= array(2) {     ["title"]= string(38) "My title"     ["date"]= string(31) "Mon, 16 Jun 2010 06:55:57 +0200" } 

What I want to do is order the two items by date.

  1. Is it possible to sort by date, when the sort value is inside every item?
  2. Do I need to convert the date format to timestamp?

What I don't want to do

I could use date and set it as the ID but that don't feel right, because two items can have the same date and then it would not be unique.

like image 469
Jens Törnell Avatar asked Jun 19 '11 09:06

Jens Törnell


2 Answers

You don't need to convert your dates to timestamps before the sorting, but it's a good idea though because it will take more time to sort without this step.

$data = array(     array(         "title" => "Another title",         "date"  => "Fri, 17 Jun 2011 08:55:57 +0200"     ),     array(         "title" => "My title",         "date"  => "Mon, 16 Jun 2010 06:55:57 +0200"     ) );  function sortFunction( $a, $b ) {     return strtotime($a["date"]) - strtotime($b["date"]); } usort($data, "sortFunction"); var_dump($data); 

Update

In newer PHP versions you can use arrow functions too. Here you can find a more concise version of the above:

usort($data, fn ($a, $b) => strtotime($a["date"]) - strtotime($b["date"])); 
like image 120
KARASZI István Avatar answered Sep 28 '22 08:09

KARASZI István


Use usort:

usort($array, function($a1, $a2) {    $v1 = strtotime($a1['date']);    $v2 = strtotime($a2['date']);    return $v1 - $v2; // $v2 - $v1 to reverse direction }); 
like image 39
phihag Avatar answered Sep 28 '22 10:09

phihag