Reputation: 67
I want to sort this JSON array by highest value in the imdb undervalue.
[{
"name": "Space home",
"year": 2012,
"plot": "Ghost dies in fire",
"run": 103,
"run_category": "1",
"rated": "PG-13",
"imdb": 83,
"meta": 82,
"genre": "001 002 003",
"tags": "test",
"source": "movie123",
"id": 6483953
}, {
"name": "Epaaoon",
"year": 2016,
"plot": "Space dies in fire",
"run": 153,
"run_category": "2",
"rated": "R",
"imdb": 64,
"meta": 54,
"genre": "001 006 007",
"tags": "test2",
"source": "movie423",
"id": 7352753
}]
I have tried:
usort($data, function($a, $b) { function
return $a->imdb > $b->imdb ? -1 : 1; });
which I found here, but I cant get it to work and I have no idea why. Any help much appreciated.
EDIT:
<?php $url = $_SERVER['DOCUMENT_ROOT'] . '/../data.json';
$data = json_decode(file_get_contents($url), true);
usort($data, function($a, $b) { //Sort the array using a user defined function
return $a->meta > $b->meta ? -1 : 1; //Compare the scores
});
print_r($data);
?>
Upvotes: 2
Views: 453
Reputation: 781088
Either get rid of the true
argument to json_decode()
, or use $a['meta']
and $b['meta']
in the comparison function. The second argument to json_decode()
tells it to convert JSON objects to PHP associative arrays rather than objects.
Upvotes: 2