Suppose I have an array that mimics a database table. Each array element represents a row, and within each row is another array that contains the field names and values.
Array
(
[0] => Array
(
[name] => 'Sony TV'
[price] => 600.00
)
[1] => Array
(
[name] => 'LG TV'
[price] => 350.00
)
[2] => Array
(
[name] => 'Samsung TV'
[price] => 425.00
)
}
What I want to do is sort the rows (outer array elements) by price. Below is an example of what I want to achieve:
Array
(
[0] => Array
(
[name] => 'LG TV'
[price] => 350.00
)
[1] => Array
(
[name] => 'Samsung TV'
[price] => 425.00
)
[2] => Array
(
[name] => 'Sony TV'
[price] => 600.00
)
}
As you can see, I don't need to preserve the keys of the outer array.
This is basically the same as the accepted answer, but a couple of new features have been added to PHP over the years to make it more convenient to use
usort
for this.You can now use an anonymous function for the comparison callback (as of PHP 5.3), and PHP 7 introduced the combined comparison operator (
<=>
), which allows you to reduce the comparison logicto a single expression
You can create a function yourself like the one below
private function orderArrayBycolumn($array, $column){
You need to use usort, a function that sorts arrays via a user defined function. Something like:
You can use
usort()
:Even better if you create a class like this to reuse the code:
This way, you can easily sort by other fields.
And although you said the the keys of the outer array don't have to be preserved you can easily achieve this by using
uasort()
instead ofusort
.You can use the usort function with a callback
http://www.php.net/manual/en/function.usort.php
I just want to make a couple additions...
@rf1234's answer is probably what I would go for (because I read somewhere that
array_multisort()
outperformsusort()
, but I haven't personally benchmarked them), but the sorting direction does not need to be declared because the default direction is ASC.Code: (Demo)
@Don'tPanic's answer using
usort()
with the spaceship operator is also attractive. From PHP7.4, the syntax can be reduced and theuse()
expression can be removed by using arrow function syntax. This technique allows$column
to freely enter the function scope withoutuse()
.Code: (Demo)
I recommend either of these correct, efficient, direct solutions.