Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 按最大值对JSON排序_Php_Json_Sorting - Fatal编程技术网

Php 按最大值对JSON排序

Php 按最大值对JSON排序,php,json,sorting,Php,Json,Sorting,我想按imdb低估值中的最高值对这个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

我想按imdb低估值中的最高值对这个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; });
我在这里找到的,但我不能让它工作,我不知道为什么。非常感谢您的帮助

编辑:



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

我认为您的代码中缺少更多内容。你能发布一个更完整的例子吗?对不起!使用完整的php代码更新。由于您使用
true
作为第二个参数,因此对于
json\u decode()
,元素是数组,而不是对象。所以它是
$a['meta']
,而不是
$a->meta
。你通过一个对象访问它,但你把它解码成一个数组。应该比较$a['meta']>$b['meta']谢谢!成功了!
<?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); 
?>