[Solved] PHP sort array by date and character


Here’s an example multi-sort using usort and a callback:

<?php
$arr = [
    ['date' => '2017-10-18', 'char' => 'Z'],
    ['date' => '2017-10-17', 'char' => 'Z'],
    ['date' => '2017-9-2', 'char' => 'A'],
    ['date' => '2017-10-17', 'char' => 'A'],
    ['date' => '2017-10-18', 'char' => 'A'],
];

usort($arr, function($a, $b) {
    $date_a = strtotime($a['date']);
    $date_b = strtotime($b['date']);

    if($date_a < $date_b)
        return -1;

    if($date_a > $date_b)
        return 1;

    $char_a = $a['char'];
    $char_b = $b['char'];

    if($char_a == $char_b)
        return 0;

    return $char_a < $char_b ? -1 : 1;
});

var_dump($arr);

First you compare the dates. Only if they are equal do you compare the chars.

The above would output:

array(5) {
  [0] =>
  array(2) {
    'date' =>
    string(8) "2017-9-2"
    'char' =>
    string(1) "A"
  }
  [1] =>
  array(2) {
    'date' =>
    string(10) "2017-10-17"
    'char' =>
    string(1) "A"
  }
  [2] =>
  array(2) {
    'date' =>
    string(10) "2017-10-17"
    'char' =>
    string(1) "Z"
  }
  [3] =>
  array(2) {
    'date' =>
    string(10) "2017-10-18"
    'char' =>
    string(1) "A"
  }
  [4] =>
  array(2) {
    'date' =>
    string(10) "2017-10-18"
    'char' =>
    string(1) "Z"
  }
}

To do a descending sort you’d just flip the -1 and 1 being returned by the comparison.

solved PHP sort array by date and character