Monday 3 September 2018

How to sort an object array based on object key values ​​in PHP?

Given an array of objects where each object in the array looks like this:

  "success": true,
  "data": [
    {
      "doctor_id": 4, -- Use this id for getting in method get inquiry doctor offers.
      "clinic": "John",
      "distance": "10 mile"
      "city": "Los Angeles",
      "price": "123",
      "photo": false,
      "rating": {
        "stars": null,
        "reviews": null
      },
      "add_info"=> "Some information",
      "time_after_create": 942 -- in seconds.
    }
  ]

is there any methodology in php that will allow me to sort by $data->price low to high and high to low, and then also sort by $data->rating->starswhere stars is a number between 0 and 5?
I took a look at the answer here which talks about array_multisort().
but I'm not sure if it achieves what I am looking for.
Any thoughts or insights are welcome.

Use usort, here's an example:
function cmp($a, $b)
{
    return strcmp($a->name, $b->name);
}

usort($your_data, "cmp");

In your case, I can propose quickly the solution following :
function cmp($a, $b)
{
    if ($a->price == $b->price) {
        return 0;
    }
    return ($a->price < $b->price) ? -1 : 1;
}
usort($your_data, array($this, "cmp"));

0 comments:

Post a Comment