3

I have array:

$array = array(array('2012-12-12', 'vvv'), array('2012-12-14', 'df'),array('2012-12-10', 'vvv'),array('2012-12-11', 'vvv'));

Array
(
    [0] => Array
        (
            [0] => 2012-12-12
            [1] => vvv
        )

    [1] => Array
        (
            [0] => 2012-12-14
            [1] => df
        )

    [2] => Array
        (
            [0] => 2012-12-10
            [1] => vvv
        )

    [3] => Array
        (
            [0] => 2012-12-11
            [1] => vvv
        )

)

http://codepad.org/gxw2yKMU

is possible to sort this with dates DESC? For this example should be:

$array[1] //2012-12-14
$array[0] //2012-12-12
$array[3] //2012-12-11
$array[2] //2012-12-10

For me the best way is use embedded functions for PHP, but how? :)

  • possible duplicate of [How do I sort a multidimensional array in php](http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php) -- it's even about sorting a multidimensional array by date in descending order... – Felix Kling Aug 02 '12 at 09:33

3 Answers3

3

You can use usort with a custom function. If you're on PHP < 5.3 you'll need a named function rather than, as I have, an anonymous one.

$array = array(
    array('2012-12-12', 'vvv'),
    array('2013-12-14', 'df'),
    array('2012-12-14', 'df'),
    array('2012-12-10', 'vvv'),
    array('2012-12-11', 'vvv')
);

usort($array, function($a, $b) {
    if ($a[0] == $b[0]) return 0;
    return ($a > $b) ? -1 : 1;
});
print_r($array);
Mitya
  • 33,629
  • 9
  • 60
  • 107
3

You should be able to use usort

usort( $array, 'sortFunction' );

function sortFunction( $a, $b ) {
    if( $a[0] == $b[0] )
        return 0;
    return ( $a[0] > $b[0] ? return -1 : 1 );
}
Krycke
  • 3,106
  • 1
  • 17
  • 21
2

You can use array_multisort() :

foreach ($array as $key => $row) {
    $dates[$key] = $row[0]; 
}
array_multisort($dates, SORT_DESC, $array);

First, you put out all dates in a new array. Then, array_multisort() will sort the second array ($array) in the same order than the first ($dates)

zessx
  • 68,042
  • 28
  • 135
  • 158