Search This Blog

Friday, June 1, 2012

Sort a multi-dimensional array in PHP


$preparedReport = array(

 0=>array('name'=>'Alf','revenue'=>1000),
 1=>array('name'=>'Boor','revenue'=>3000),
 2=>array('name'=>'Cat','revenue'=>4000),
);

usort($preparedReport, 'sortByRevenueOrder');

// use $this in object context 
//usort($preparedReport, array($this, 'sortByRevenueOrder'));

function sortByRevenueOrder($a, $b) {

        if ($a['revenue'] == $b['revenue']) {
            return 0;
        }
        
            return ($a['revenue'] > $b['revenue']) ? 1 : -1; // ascending order
        
         //   return ($a['revenue'] < $b['revenue']) ? 1 : -1; descending order 
       
}

No comments: