Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Table formatted data multi-column sort
- *
- * Not all data can be easily aggregated/filtered/sorted by data sources
- * Typically this is due to having to aggregate data from multiple data sources (via a Domain Model hopefully)
- * (e.g. we must aggregate user data from a relational db, mongo db, and google services)
- */
- $tableFormatedData = array(
- array('column1'=>'Foo', 'column2'=>'Bar', 'column3'=>'...', ...),
- array('column1'=>'Zoo', 'column2'=>'Zar', 'column3'=>'...', ...),
- array('column1'=>'Zoo', 'column2'=>'Zar', 'column3'=>'...', ...),
- );
- /**
- * @var array user input (perhaps via ajax call from a client side data table widget)
- */
- $ordering = array(
- 'column1'=>'asc',
- 'column2'=>'desc',
- 'column3'=>'desc'
- );
- /**
- * @see http://www.php.net/manual/en/function.usort.php
- */
- usort($tableFormatedData, function($rowA, $rowB) use ($ordering) {
- foreach($ordering as $key=>$sortDirection){
- switch($sortDirection){
- case 'desc':
- $direction=-1;
- break;
- case 'asc':
- default:
- $direction=1;
- break;
- }
- if ($rowA[$key] > $rowB[$key]) {
- return $direction;
- } else if ($rowA[$key] < $rowB[$key]){
- return $direction*-1;
- }
- }
- return 0;
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement