ndAR
ndAR

Reputation: 371

Sort multidimensional array by value not sorting correctly

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 !.

Upvotes: 0

Views: 83

Answers (2)

fusion3k
fusion3k

Reputation: 11689

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.

Upvotes: 1

Matt
Matt

Reputation: 5428

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

Upvotes: 1

Related Questions