Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to usort and maintain keys?

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?

like image 878
StackOverflowNewbie Avatar asked Mar 19 '15 23:03

StackOverflowNewbie


People also ask

Is PHP Usort stable?

Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.

How does Usort work in PHP?

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.

What function is used to sort the values in array and keep the keys intact?

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.

How do you Unsort an array in PHP?

PHP usort() Function $a=array(4,2,8,6); usort($a,"my_sort");


1 Answers

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.

like image 89
John Conde Avatar answered Oct 03 '22 02:10

John Conde