I need to sort some data that is not coming from a database, but is structured like a sql result set.
In MySQL, I would write a query as follows to sort the data by two columns:
SELECT product, qty FROM stock ORDER BY qty DESC, LENGTH(product) DESC
However, in this case, I need to perform this sorting logic with php. Specifically, the rows are sorted first by descending qty, and then by the length of name descending.
Unsorted Input:
[
['name' => 'foo bar', 'qty' => 6],
['name' => 'foo bar bar foo', 'qty' => 10],
['name' => 'b', 'qty' => 5],
['name' => 'foo', 'qty' => 10],
['name' => 'bar', 'qty' => 6],
['name' => 'foo bar bar bar foo', 'qty' => 6],
]
After sorting, I need to restructure the data with the name values as keys and the qty values as values of a flat, associative array
The finished array would look something like this:
Desired Output:
[
'foo bar bar foo' => 10,
'foo' => 10,
'foo bar bar bar foo' => 6,
'foo bar' => 6,
'bar' => 6,
'b' => 5
]
Looking at the answers to this question: PHP array multiple sort – by value then by key?, it seems
array_multisortis the way to go. (I’m not really sure howarray_multisortworks, I just kinda hacked this up, and it seems to work).Try this:
Demo: http://codepad.org/mAttNIV7
UPDATE: Added
array_mapto make it sort by the length of the string, before it was just doing:$str1 > $str2instead ofstrlen($str1) > strlen($str2).UPDATE 2: In PHP >= 5.3, you can replace
create_functionwith a real anonymous function.Demo 2: http://codepad.viper-7.com/6qrFwj