0

I'm trying to sort a multidimensional array by date ASC but i'm having troubles with... so i would like to ask you guys and girls why this happens?

my code is (Run at: Codepad example ):

$data = array (
          array (
            'date' => '2016-03-11 12:10:17',
            'type' => '1'
          ),
          array (
            'date' => '2016-03-12 07:16:25',
            'type' => '1'
          ),
          array (
            'date' => '2016-03-12 07:18:07',
            'type' => '2'
          ),
          array (
            'date' => '2016-03-09 14:57:42',
            'type' => '2'
          ),
          array (
            'date' => '2016-02-22 10:39:39',
            'type' => '1'
          )
    );
    usort($data, function($a, $b) {
        return $a['date'] - $b['date'];
    });
    echo '<pre>';
    var_dump($data);

The issue is that the sorting is not good, i mean it need to be from February to March and is not doing this and i can't find why.

Any help is very appreciated !.

1
  • What isn't working exactly? Do you have any errors? What have you tried to fix it? Please read and follow the instructions on this page to produce a high-quality question: stackoverflow.com/help/how-to-ask Commented Mar 31, 2016 at 18:02

2 Answers 2

1

Use the sort from the docs: http://php.net/manual/en/function.usort.php

usort($data, function($a, $b) {
    if ($a['date'] == $b['date']) {
        return 0;
    }
    return ($a['date'] < $b['date']) ? -1 : 1;
});
Sign up to request clarification or add additional context in comments.

Comments

1

You compare strings, not number, so you have unexpected results.

To compare two strings, you can use strcmp:

usort( $data, function( $a, $b ) {
    return strcmp( $a['date'], $b['date'] );
});

strcmp returns < 0 if first arg is less than second; > 0 if first arg is greater than second, and 0 if they are equal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.