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
)
)
A usort
callback should return 3 types of values, depending on the circumstances:
$a
is less than $b
$b
is less than $a
$a
and $b
are equalusort($presentations, function($a, $b)
{
if($a['date'] == $b['date'])
{
return 0;
}
return $a['date'] < $b['date'] ? -1 : 1;
});
You can use usort()
to apply a custom comparison function.
usort($presentations,
function ($left, $right) {
return $left['date'] - $right['date'];
});
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']);
});