sorting an associative array by boolean field
$list
is populated thusly: -
$list[$i++] = array(
"date" => $date,
"desc" => $desc,
"开发者_StackOverflowpriority" => $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.
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
Use usort and supply your own sort function describing whether true is greater then false or the other way around.
function cmp($a, $b)
{
return ($a['priority'] > $b['priority']) ? 1 : -1;
}
usort($array, "cmp");
if you want to change the stability of the sort, where elements are sorted if they have the same priority value, then just modify the cmp function.
use this function
function sort2d ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE)
{
if(is_array($array) && count($array)>0)
{
foreach(array_keys($array) as $key)
$temp[$key]=$array[$key][$index];
if(!$natsort)
($order=='asc')? asort($temp) : arsort($temp);
else
{
($case_sensitive)? natsort($temp) : natcasesort($temp);
if($order!='asc')
$temp=array_reverse($temp,TRUE);
}
foreach(array_keys($temp) as $key)
(is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
return $sorted;
}
return $array;
}
and call
sort2d ($list, $priority);
Reference
精彩评论