say i have an array of objects:
Array (
[0] => stdClass Object (
[id] => 1
[name] => product_1
[cost] =>9.99
)
[1] => stdClass Object (
[id] => 2
[name] => product_2
[cost] =>2.99
)
[2] => stdClass Object (
[id] => 3
[name] => product_3
[cost] =>4.99
)
[3] => stdClass Object (
[id] => 4
[name] => product_4
[cost] =>1.99
)
[4] => stdClass Object (
[id] => 5
[name] => product_5
[cost] =>0.99
)
)
I want to order them starting from the lowest cost to the highest however the first element in the array has to have the [name] of “product_3”.
To do this, you can’t rely on sorting alone. You’d need a bit more logic:
usort().array_unshift().So, for #1, you can do a bunch of things. The simplest is to loop the array to find the key that indexes where the first object is, and
unset()it:Now you have the first element in
$first, so you have to sort the array withusort():Finally, add the first element back to the beginning of the now-sorted array:
Disclaimer: None of the above implementation was tested.