Created
March 23, 2015 12:57
-
-
Save jveldboom/8fdb3ac9ee685a1f405a to your computer and use it in GitHub Desktop.
Sort Multidimensional Array by Sub-Array Key’s Value (http://www.bitrepository.com/php-sort-multidimensional-array-sub-array-key-value.html)
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
$array = array( | |
array( | |
'name' => 'Lorem Ipsum', | |
'position' => 4 | |
), | |
array( | |
'name' => 'Just a title', | |
'position' => 3 | |
), | |
array( | |
'name' => 'Dummy title here', | |
'position' => 5 | |
) | |
); | |
$sort = new SortMdArray; | |
$sort->sortByKey($array); | |
echo '<pre>'; print_r($array); echo '</pre>'; | |
$sort = new SortMdArray; | |
$sort->sort_order = 'desc'; // from highest to lowest | |
$sort->sort_key = 'quantity'; | |
$sort->sortByKey($array); |
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
class SortMdArray { | |
public $sort_order = 'asc'; // default | |
public $sort_key = 'position'; // default | |
public function sortByKey(&$array) { | |
usort($array, array(__CLASS__, 'sortByKeyCallback')); | |
} | |
function sortByKeyCallback($a, $b) { | |
if($this->sort_order == 'asc') { | |
$return = $a[$this->sort_key] - $b[$this->sort_key]; | |
} else if($this->sort_order == 'desc') { | |
$return = $b[$this->sort_key] - $a[$this->sort_key]; | |
} | |
return $return; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment