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.

Community
  • 1
  • 1
m.chiang
  • 185
  • 1
  • 8
  • http://stackoverflow.com/questions/1597736/how-to-sort-an-array-of-associative-arrays-by-value-of-a-given-key-in-php? My favourite would be the second answer – Mister Henson Jul 06 '16 at 18:05

2 Answers2

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)

SanjiMika
  • 2,664
  • 19
  • 19
  • 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 Jul 06 '16 at 20:23
  • @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 – SanjiMika Jul 06 '16 at 21:15
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.

Mahdyfo
  • 1,155
  • 7
  • 18
  • 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 Jul 06 '16 at 18:13
  • @m.chiang yes, if it will be all arrays instead of objects, I think you can array_multisort() it easier – Mahdyfo Jul 06 '16 at 18:15