Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.