m.chiang
m.chiang

Reputation: 185

How to sort an Array of Objects 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.

Upvotes: 0

Views: 80

Answers (2)

SanjiMika
SanjiMika

Reputation: 2714

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"));

Note : "cmp" is the function callable (it must be used for PHP >5.3)

Upvotes: 1

Mahdyfo
Mahdyfo

Reputation: 1173

Maybe you should use $assoc parameter when decoding this json. It will give you the data as an array instead of an object so you can sort that array. json_decode

$array1 = json_decode($input, TRUE);

I think it can be also helpful if you read about Object Iteration in php.

Upvotes: 0

Related Questions