Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting an associative array by boolean field

Tags:

php

sorting

$list is populated thusly: -

$list[$i++] = array(
    "date" => $date,
    "desc" => $desc,
    "priority" => $priority
);

$priority is set to TRUE if it matches some criteria.

I'd like the $list to be sorted with rows that have a priority TRUE at the top.

The list is already sorted by date which I wish to preserve.

like image 503
martin blank Avatar asked Dec 04 '22 08:12

martin blank


1 Answers

In PHP>=5.3

usort ($array, function ($left, $right) {
    return $left['priority'] - $right['priority'];
});

Or in earlier version

function cmp($left, $right) {
    return $left['priority'] - $right['priority'];
}
usort($array, 'cmp');

Or use create_function() (also for version < 5.3)

usort ($array, create_function('$left,$right', 'return $left[\'priority\'] - $right[\'priority\'];'));

This works, because (int) true === 1 and (int) false === 0

true - true == 0
true - false == 1
false - true == -1
false - false == 0
like image 171
KingCrunch Avatar answered Dec 26 '22 05:12

KingCrunch