Home » Php » arrays – PHP: how to usort and maintain keys?

arrays – PHP: how to usort and maintain keys?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

Try with this:

<?php

$json = '{
  "23": {
    "price": "33.99"
  },
  "38": {
    "price": "30.86"
  },
  "51": {
    "price": "31.49"
  }
}';

$array = json_decode($json, true);
asort($array);

print_r($array);

?>