Last active
August 29, 2015 13:56
-
-
Save chazmead/8829079 to your computer and use it in GitHub Desktop.
/** * Sort a 2 dimension array with values in the second dimension * * Order can be string of a field, which will default to asc * OR as array(field1,field2...fieldn) each defaulting to asc * OR as assoc array(field1 => dir[asc|desc], field2 => dir[asc|desc]...fieldn * => dir[asc|desc]) * * PHP Sort constants can be used: SORT_ASC | SORT_DESC * * …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Sort a 2 dimension array with values in the second dimension | |
* | |
* Developer: chazmead89@gmail.com // @RaggaMuffin-4201 | |
* | |
* Order can be string of a field, which will default to asc | |
* OR as array(field1,field2...fieldn) each defaulting to asc | |
* OR as assoc array(field1 => dir[asc|desc], field2 => dir[asc|desc]...fieldn | |
* => dir[asc|desc]) | |
* | |
* PHP Sort constants can be used: SORT_ASC | SORT_DESC | |
* | |
* @param array $array array to sort - passed by reference | |
* @param mixed $order | |
* @return null | |
*/ | |
function multisort(&$array,$order) { | |
usort($array, function($a,$b) use ($order) { | |
$sortMap = array('asc'=>SORT_ASC,'desc'=>SORT_DESC); | |
$aObj = (object)$a; | |
$bObj = (object)$b; | |
if (is_string($order)) | |
$order = array($order); | |
if (is_object($order)) | |
$order = (array)$order; | |
$i = 0; | |
$cOrder = count($order); | |
foreach($order as $field => $dir) { | |
if (is_numeric($field)) { | |
$field = $dir; | |
$dir = SORT_ASC; | |
} | |
// Goto next step when a mis-match is found. | |
if ($aObj->$field != $bObj->$field) | |
break; | |
// All fields match return 0 | |
if (++$i === $cOrder) | |
return 0; | |
} | |
if(!is_numeric($dir)) { | |
$dir = strtolower($dir); | |
$dir = $sortMap[$dir]; | |
} | |
$d = ($dir === SORT_DESC) ? -1 : 1; | |
$c = ($aObj->$field < $bObj->$field) ? -1 : 1; | |
return $c*$d; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment