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 question is a bit old, but will leave the answer here for future.
From php.net-Multisort function we can use the code below;
The above is for a static sorting of data where you manually change sort columns.
For more dynamic and robust example consider below;
Assume I have the data below;
If we need to sort the above array data out of the box, then we can set the sort orders in an array using the syntax;
This means sort column 1 ASC, column 4 DESC then column 3 ASC. We can then using the function below to sort our multidimension database data;
Then we can use it as below;
For key value array data
E.g. $data=[['c1'=>1212,'c2'=>'mynames'],...];
Use the order as$order=['c1'=>'desc','c10'=>'asc'];
I tested the above with an array of 1000 records. Hope it helps someone.
It is just a one liner
You can find it here as well: http://php.net/manual/en/function.array-multisort.php
search for "array_column" on that manual page.