Created
February 19, 2011 20:26
-
-
Save quilime/835336 to your computer and use it in GitHub Desktop.
Simple Multi-Dimensional Key Sort
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 | |
/* | |
A simple multidimensional key-value sorting function, allowing you to sort an | |
array by a multidimensional key without having to write callback functions. | |
This concept appears to be missing in PHP, this function allows for easy array | |
sorting. Works with both strings and numbers, case sensitive and doesn't | |
drop/mash keys. PHP 5.3.0 > only. | |
via: http://projects.westhost.com/contest/php/function/simple-multi-dimensional-key-sort/151 | |
*/ | |
function msort ($data, $k, $options = array()) { | |
usort($data, function($a, $b) use (&$k, &$options) { | |
list($a,$b) = ((isset($options['DESC']) && $options['DESC'] == True) ? | |
array($a[$k], $b[$k]) : array($b[$k], $a[$k])); | |
if ($a == $b) return 0; | |
if (is_string($a) && is_string($b)) { | |
return strcmp(strtolower($b), strtolower($a)); | |
} else { | |
return ($a > $b) ? -1 : 1; | |
} | |
}); | |
return $data; | |
} | |
// USAGE | |
// $data = msort($data, 'key', $sortArgs); | |
// $sortArgs only takes one variable presently, but could be easily extended for further functionality: | |
// $sortArgs = array ('DESC'=>True); // Sort in Descending order | |
// $sortArgs = array ('DESC'=>False); or, $sortArgs = NULL; // Sort in Ascending order | |
// EXAMPLES | |
// | |
// $fruits = array( | |
// array('name'=>'PiNeApPlE', 'qty'=>11), | |
// array('name'=>'pineapple', 'qty'=>2), | |
// array('name'=>'apple', 'qty'=>72), | |
// array('name'=>'lime', 'qty'=>9), | |
// array('name'=>'starfruit', 'qty'=>1), | |
// array('name'=>'coconut', 'qty'=>3), | |
// array('name'=>'banana', 'qty'=>12) | |
// ); | |
// | |
// $fruits = msort($fruits, 'qty', array('DESC'=>True)); | |
// $fruits = msort($fruits, 'name'); | |
// $fruits = msort($fruits, 'name', array('DESC'=>True)); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment