$date, "desc" => $desc, "priority" => $pr...">

Sort associative array by logical field

$list filled in this way: -

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

$priorityset to TRUEif it meets certain criteria.

I would like to $listsort with priority lines TRUEat the top.

The list is already sorted by the date I want to keep.

+3
source share
3 answers

In PHP> = 5.3

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

Or in an 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\'];'));

It works because (int) true === 1and(int) false === 0

true - true == 0
true - false == 1
false - true == -1
false - false == 0
+10
source

Use usort and put in your own sort function that describes whether true is greater than false or vice versa.

function cmp($a, $b)
{
    return ($a['priority'] > $b['priority']) ? 1 : -1;
}

usort($array, "cmp");

, , , cmp.

0

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

sort2d ($ list, $priority);

0

All Articles