How to sort date array in php?

I'm new to php, I have php date array

[0] => 11-01-2012
[1] => 01-01-2014
[2] => 01-01-2015
[3] => 09-02-2013
[4] => 01-01-2013

I want to sort it as:

[0] => 11-01-2012
[1] => 01-01-2013
[2] => 09-02-2013
[3] => 01-01-2014
[4] => 01-01-2015

I use asortbut do not work.

+11
source share
5 answers

Since the elements of the array are strings, you need to convert them to a date and then compare with sorting. usort()sort the array using a custom function, which is a good sort function for this case.

$arr = array('11-01-2012', '01-01-2014', '01-01-2015', '09-02-2013', '01-01-2013');    
function date_sort($a, $b) {
    return strtotime($a) - strtotime($b);
}
usort($arr, "date_sort");
print_r($arr);

Check the result in the demo

+25
source

use time-use function to generate ts and sort

<?php
  $out = array();
  // $your_array is the example obove
  foreach($your_array as $time) {
  $out[strtotime($time)] = $time;
  }
  // now $out has ts-keys and you can handle it

  ...
 ?>

ksort

+1
source

Try it,

<?php 
$array = [ '11-01-2012', '01-01-2014', '01-01-2015', '09-02-2013', '01-01-2013' ];
function sortFunction( $a, $b ) {
    return strtotime($a) - strtotime($b);
}
usort($array, "sortFunction");
var_dump( $array );
?>

Will sort the dates in the desired order.

+1
source

Try the code below:

<?php 

$array = array('11-01-2012','01-01-2011','09-02-2013','01-01-2014','01-01-2015');

function cmp($a, $b)
{
    $a = date('Y-m-d', strtotime($a));
    $b = date('Y-m-d', strtotime($b));

    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}
usort($array, "cmp");

foreach ($array as $key => $value) {
    echo "[$key]=> $value <br>";
}
?>
+1
source

use DateTime for the sort date:

$a = array(
    new DateTime('2016-01-02'),
    new DateTime('2016-05-01'),
    new DateTime('2015-01-01'),
    new DateTime('2016-01-01')
);
asort($a);
var_dump($a);

The conclusion will be:

array(4) {
  [2]=>
  object(DateTime)#3 (3) {
    ["date"]=>
    string(26) "2015-01-01 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(10) "US/Pacific"
  }
  [3]=>
  object(DateTime)#4 (3) {
    ["date"]=>
    string(26) "2016-01-01 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(10) "US/Pacific"
  }
  [0]=>
  object(DateTime)#1 (3) {
    ["date"]=>
    string(26) "2016-01-02 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(10) "US/Pacific"
  }
  [1]=>
  object(DateTime)#2 (3) {
    ["date"]=>
    string(26) "2016-05-01 00:00:00.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(10) "US/Pacific"
  }
}
-1
source

Source: https://habr.com/ru/post/1660052/


All Articles