I have the following array (JSON-ified for ease of viewing):
{
"23": {
"price": "33.99"
},
"38": {
"price": "30.86"
},
"51": {
"price": "31.49"
}
}
I want to sort this by the price
key, but I want the results to also return the key of the element that contains the price, so something like this:
{
"38": {
"price": "30.86"
},
"51": {
"price": "31.49"
},
"23": {
"price": "33.99"
}
}
My usort
callback is this:
private function _price_sort($a, $b)
{
if ($a['price'] == $b['price']) {
return 0;
}
return ($a['price'] < $b['price']) ? -1 : 1;
}
... which returns the array in the correct order, but without the element container:
[
{
"price": "30.86"
},
{
"price": "31.49"
},
{
"price": "33.99"
}
]
Is there something I need to do in the callback function or in usort to retain the keys?
Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.
The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.
The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.
PHP usort() Function $a=array(4,2,8,6); usort($a,"my_sort");
Use uasort()
to maintain your keys
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With