0

I've got a multi dimensional array as seen below. I want to sort the 2nd level arrays based the [date] attribute. I believe I can use array_multisort, but I'm unsure of how to proceed.

My array is in the variable $presentations

Array
(
    [0] => Array
        (
            [date] => 20111104
            [name] => Name of Presentation
        )

    [1] => Array
        (
            [date] => 20111118
            [name] => sadf
        )

    [2] => Array
        (
            [date] => 20100427
            [name] => older one
        )

    [3] => Array
        (
            [date] => 20101213
            [name] => Another one from 2010
        )

    [4] => Array
        (
            [date] => 20110719
            [name] => sdf
        )

    [5] => Array
        (
            [date] => 20110614
            [name] => Sixth one
        )

)
wesbos
  • 25,839
  • 30
  • 106
  • 143
  • possible duplicate of [Sorting multidimensional array in PHP](http://stackoverflow.com/questions/2059255/sorting-multidimensional-array-in-php) – Michael Berkowski Nov 04 '11 at 19:37
  • You'll want to use `usort()` with a callback. See linked question. – Michael Berkowski Nov 04 '11 at 19:38
  • I checked that out but would like some help with this specific case. I help out my fair share on SO, so please dont close this. – wesbos Nov 04 '11 at 19:39
  • Tim Cooper's answer below is spot on then. – Michael Berkowski Nov 04 '11 at 19:41
  • @Wes I added an answer that uses native PHP functions (C functions, actually). Tim's answer does the comparison twice for values that are not equal (which is not usually the case). My answer does 1 comparison and is therefor faster. However, performance may not matter in this case. It's also case-insenstive, something Tim's code does not do. – Levi Morrison Nov 04 '11 at 21:40

3 Answers3

2

A usort callback should return 3 types of values, depending on the circumstances:

  • A negative number if parameter $a is less than $b
  • A positive number if parameter $b is less than $a
  • Zero if both $a and $b are equal
usort($presentations, function($a, $b)
{
    if($a['date'] == $b['date'])
    {
        return 0;
    }
    return $a['date'] < $b['date'] ? -1 : 1;
});
  • Simple: if they are equal, return 0, if it is less than, return a negative number, if it's greater than, return a positive number. This is how sorting algorithms typically work. – Levi Morrison Nov 04 '11 at 19:46
1

You can use usort() to apply a custom comparison function.

usort($presentations, 
      function ($left, $right) {
          return $left['date'] - $right['date'];
      });
David Harkness
  • 35,992
  • 10
  • 112
  • 134
1

Here's a string implementation which works with integers in PHP because of type juggling:

usort($presentations, function($a, $b) {
    return strcmp($a['date'], $b['date']);
});
Levi Morrison
  • 19,116
  • 7
  • 65
  • 85