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
]