0

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.

1

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

This works for sorting the items from price low to high, which is fantastic. How do I sort from high to low?? I tried changing the < to > and switching the ? -1 : 1; but it didn't work. Edit: nevermind, found out how to do it. Will approve answer in a few minutes. Thank you!
@m.chiang If I'm not wrong, you've already changed two clauses here $a<$b and -1 : 1, then logically it comes back the same things :) Normally for sort from high to low, you need just to change the '<' into '>' in IF clause. Good luck :) p/s: I received well your vote. Thanks
0

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.

2 Comments

The data is already put through json_decode. And it comes back as an array containing objects. So you're suggesting converting it to an array containing arrays?
@m.chiang yes, if it will be all arrays instead of objects, I think you can array_multisort() it easier

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.