Advertisement
LanceCaraccioli

PHP Multidimensional, Multi-Column Array Sort

Oct 16th, 2013
775
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.33 KB | None | 0 0
  1. /**
  2.  * Table formatted data multi-column sort
  3.  *
  4.  * Not all data can be easily aggregated/filtered/sorted by data sources
  5.  * Typically this is due to having to aggregate data from multiple data sources (via a Domain Model hopefully)
  6.  * (e.g. we must aggregate user data from a relational db, mongo db, and google services)
  7.  */
  8.  
  9. $tableFormatedData = array(
  10.     array('column1'=>'Foo', 'column2'=>'Bar', 'column3'=>'...', ...),
  11.     array('column1'=>'Zoo', 'column2'=>'Zar', 'column3'=>'...', ...),
  12.     array('column1'=>'Zoo', 'column2'=>'Zar', 'column3'=>'...', ...),
  13. );
  14.  
  15. /**
  16.  * @var array user input (perhaps via ajax call from a client side data table widget)
  17.  */
  18. $ordering = array(
  19.     'column1'=>'asc',
  20.     'column2'=>'desc',
  21.     'column3'=>'desc'
  22. );
  23.  
  24. /**
  25.  * @see http://www.php.net/manual/en/function.usort.php
  26.  */
  27. usort($tableFormatedData, function($rowA, $rowB) use ($ordering) {
  28.     foreach($ordering as $key=>$sortDirection){
  29.         switch($sortDirection){
  30.             case 'desc':
  31.                 $direction=-1;
  32.                 break;
  33.             case 'asc':
  34.             default:
  35.                 $direction=1;
  36.                 break;
  37.         }
  38.         if ($rowA[$key] > $rowB[$key]) {
  39.             return $direction;
  40.         } else if ($rowA[$key] < $rowB[$key]){
  41.             return $direction*-1;
  42.         }
  43.     }
  44.     return 0;
  45. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement