Skip to content

Instantly share code, notes, and snippets.

@jveldboom
Created March 23, 2015 12:57
Show Gist options
  • Save jveldboom/8fdb3ac9ee685a1f405a to your computer and use it in GitHub Desktop.
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)
$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);
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