Search code examples
phparrayssortingmultidimensional-array

Sort a 2d array by a column DESC


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

Is it possible to sort this by 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

Solution

  • 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)