Skip to content

Instantly share code, notes, and snippets.

@austinjreilly
Created August 4, 2014 14:56
Show Gist options
  • Save austinjreilly/f8fd5aeef34a7f054277 to your computer and use it in GitHub Desktop.
Save austinjreilly/f8fd5aeef34a7f054277 to your computer and use it in GitHub Desktop.
Sort Multi-Dimensional Array By Value In PHP
<?php
/**
* Sort Multi Dimensional Array by value in PHP
*
* @link http://www.paulund.co.uk/sort-multi-dimensional-array-value
*/
// Original array
Array
(
[item-1] => Array
(
[id] => 1
[title] => Item 1
[order] => 3
)
[item-2] => Array
(
[id] => 2
[title] => Item 2
[order] => 2
)
[item-3] => Array
(
[id] => 3
[title] => Item 3
[order] => 1
)
)
// Pass array with callback function that defines how to order
usort($array, 'sort_by_order ');
function sort_by_order ($a, $b) {
return $a['order'] - $b['order'];
}
// Sorted array
Array
(
[item-3] => Array
(
[id] => 3
[title] => Item 3
[order] => 1
)
[item-2] => Array
(
[id] => 2
[title] => Item 2
[order] => 2
)
[item-1] => Array
(
[id] => 1
[title] => Item 1
[order] => 3
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment