1

I am looking for the best way to sort a multidimensional array, I want it sorted based on what the child array contains.

This is my array:

Array
(
    [0] => Array
        (
            [id] => 2
            [level] => 3
            [lastAction] => "String Here" 
            [actionAt] => 23/03/2014
        )

    [1] => Array
        (
            [id] => 4
            [level] => 5
            [lastAction] => "Another String here"
            [actionAt] => 24/3/2014
        )

    [2] => Array
        (
            [id] => 9
            [level] => 1
            [lastAction] => "String again"
            [actionAt] => 01/01/2013
        )

)

And I would like to sort the 3 main arrays based on the ActionAt from their child arrays, how is this possible?

I've read a bit about it and some say ksort and usort, but I have not been able to get it working properly.

Jesper Jacobsen
  • 151
  • 2
  • 13

3 Answers3

2

You will need to implement your own comparison function and use usort:

function cmp($a, $b)
{
    if ($a['actionAt'] == $b['actionAt']) {
        return 0;
    }

    //Assuming your dates are strings (http://stackoverflow.com/questions/2891937/strtotime-doesnt-work-with-dd-mm-yyyy-format)
    $atime = strtotime(str_replace('/', '-', $a['actionAt']));
    $btime = strtotime(str_replace('/', '-', $b['actionAt']));

    return ($atime < $btime) ? -1 : 1;
}

usort($array, "cmp");
SuperTron
  • 4,203
  • 6
  • 35
  • 62
  • Well, my datetime looks like this 2013-08-01 13:32:52. And when I run it, it just returns 1, instead of the order of the three arrays. – Jesper Jacobsen Aug 02 '14 at 00:52
  • well, you'll have to convert that datetime into a timestamp, then compare the two timestamps inside `cmp($a, $b)`. I used the strtotime cause if the time is formatted as dd-mm-yyyy (european standard), strtotime is smart enough to get a timestamp from it. That's why the str_replace is in there. You'll have to play with the `cmp($a, $b)` function to deal correctly with your time format. – SuperTron Aug 02 '14 at 01:00
2

If you want to use usort, you'll have to make a comparison function. Like so:

function mySort($a, $b)
{
    $dateA = new DateTime($a['actionAt']);
    $dateB = new DateTime($b['actionAt']);

    if($dateA < $dateB)
        return -1;
    elseif($dateA == $dateB)
        return 0;
    else
        return 1;
}

usort($myArray, "mySort");
1
function custom_sort($a,$b) {
    return strtolower($a['id']) > strtolower($b['id']);
}
usort($yourArray, 'custom_sort');

Note: you can change $a[] and $b[] to sort on the key you want.

kbonnelly
  • 189
  • 1
  • 1
  • 11