Wednesday, 29 August 2018

PHP: sorting a multidimensional array by an attribute

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
        )

)


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

0 comments:

Post a Comment