Answer 1, authority 100%
Sorting by custom function: usort () .
usort ($ array, function ($ a, $ b) {
return ($ a ['price'] - $ b ['price']);
});
Answer 2, authority 24%
$ data = array
(
array ('name' = & gt; 'title 1', 'price' = & gt; 200),
array ('name' = & gt; 'title 2', 'price' = & gt; 100)
);
usort
(
$ data,
create_function
(
'$ a, $ b',
'return - ($ a ["price"] - $ b ["price"]);' # return the desired value
)
);
1) do not forget that price fields must be int, not strings (otherwise, an explicit conversion is needed)
2) if you need reverse sort order:
return $ a ["price"] - $ b ["price"];
Answer 3, authority 18%
You can convert it to an array like this:
Answer 4, authority 18%
Found on the Internet:
function cmp ($ a, $ b) {
return strnatcmp ($ a ["product_order"], $ b ["product_order"]);
}
usort ($ parts, "cmp");
Answer 5, authority 6%
the uasort function is designed to be sorted using a custom function, but preserving the array keys (unlike usort).
Answer 6
I suffered for a long time with a similar problem, here is my solution:
principle:
- build another array “2” where the key of the new array = the key of the old one, and the value itself = the value by which we want to sort;
- sorting the new array “2” SAVING KEYS (asort, arsort);
- well, and then we build another array “3” based on array “2” – we go through array “2” and along the way insert into array “3” “a subarray” of array “1” by the key of array “2”;
- array “3” is our sorted one.
for ($ i = 0; $ i & lt; count ($ array); $ i ++) {
$ sortkey [$ i] = $ array [$ i] ['price'];
}
asort ($ sortkey); // ascending, arsort ($ sortkey) - descending
foreach ($ sortkey as $ key = & gt; $ key) {
$ sorted [] = $ array [$ key];
}