Sort multidimensional arrays using Uasort

I currently have several multidimensional arrays that look like this:

Array ( 
    [71] => Array ( [author] => 2 [date] => 1392867376 ) 
    [49] => Array ( [author] => 2 [date] => 1392868188 ) 
    [75] => Array ( [author] => 14 [date] => 1392867388) 
    [67] => Array ( [author] => 2 [date] => 1392870805 ) 
)

I would like to sort them by "date", but I have no idea how to do this. I tried this:

function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}
uasort($visited, 'cmp');

But since I have no idea, and could not find a link to how to use the "comparison function", I enter space. Everything I managed to find was very vague. Currently this is sorted by "author".

Can someone kindly explain to me how these comparison functions work (or point me to an online resource) and tell me what I need to do to sort this array by "date" - while keeping all the keys unchanged (the keys should not be changed or erased)

Thanks so much for the help provided.

PS: array_multisort - .

+3
2

cmp:

function cmp($a, $b) {
    if ($a['date'] == $b['date']) {
        return 0;
    }
    return ($a['date'] < $b['date']) ? -1 : 1;
}

.

+5

<?php
$a = array();
$a[71] = Array ('author' => 2, 'date' => 1392867376 );
$a[49] = Array ( 'author' => 14, 'date' => 1392868188 ) ;
$a[75] = Array ( 'author' => 2, 'date' => 1392867388) ;
$a[67] = Array ( 'author' => 2, 'date' => 1392870805 ) ;

$date = array();

// Obtain a list of columns
foreach ($a as $key => $row) {
    $date[$key]  = $row['date'];    
}

//sort the array date ascending order
array_multisort($date, SORT_ASC, $a);

//array is sorted in ascending order
print_r($a);
0

All Articles