I've got the following structue of array:
Array
(
[0] => Array
(
[configuration_id] => 10
[id] => 1
[optionNumber] => 3
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
[1] => Array
(
[configuration_id] => 9
[id] => 1
[optionNumber] => 2
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
[2] => Array
(
[configuration_id] => 8
[id] => 1
[optionNumber] => 1
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
)
What's the best way for order the array, in an incremental way based on the optionNumber?
So the results look like:
Array
(
[0] => Array
(
[configuration_id] => 8
[id] => 1
[optionNumber] => 1
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
[1] => Array
(
[configuration_id] => 9
[id] => 1
[optionNumber] => 2
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
[2] => Array
(
[configuration_id] => 10
[id] => 1
[optionNumber] => 3
[optionActive] => 1
[lastUpdated] => 2010-03-17 15:44:12
)
)
PHP 5.3+
Use
usort
.In PHP ≥5.3, you should use an anonymous function instead:
Note that both code above assume
$a['optionNumber']
is an integer. Use @St. John Johnson's solution if they are strings.In PHP ≥7.0, use the spaceship operator
<=>
instead of subtraction to prevent overflow/truncation problems.The keys are removed when using a function like the ones above. If the keys are important, the following function would maintain it... but foreach loops are pretty inefficient.
Use arsort instead of asort if you want from high to low.
Code credit: http://www.firsttube.com/read/sorting-a-multi-dimensional-array-with-php/
Use
usort
I used both solutions by KennyTM and AJ Quick and came up with a function that can help in this issue for many cases like using ASC or DESC sorting or preserving keys or if you have objects as children of array.
Here is this function (works for PHP7 and higher because of spaceship operator):
Usage:
Edit
The first part can be rewritten using
uasort()
and the function will be shorter (works for PHP7 and higher because of spaceship operator):