按最高值PHP排序JSON

时间:2017-02-17 22:42:47

标签: php json sorting

我想在imdb undervalue中按最高值对此JSON数组进行排序。

[{
    "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
}]

我试过了:

usort($data, function($a, $b) {  function
return $a->imdb > $b->imdb ? -1 : 1; });

我在这里找到了,但我不能让它工作,我不知道为什么。任何帮助非常感谢。

编辑:

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

1 个答案:

答案 0 :(得分:1)

要么取消true json_decode()参数,要么在比较函数中使用$a['meta']$b['meta']json_decode()的第二个参数告诉它将JSON对象转换为PHP关联数组而不是对象。

相关问题