【问题标题】:Sort JSON by highest value PHP按 PHP 最高值排序 JSON
【发布时间】:2017-07-07 14:41:12
【问题描述】:

我想按 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; });

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

编辑:

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

【问题讨论】:

  • 我认为您的代码还有更多我们缺少的东西。你能发布一个更完整的例子吗?
  • 对不起!更新了完整的 php 代码。
  • 由于您使用true 作为第二个参数,到json_decode(),元素是数组,而不是对象。所以它是$a['meta'],而不是$a-&gt;meta
  • 您正在通过一个对象访问它,但您已将其解码为一个数组。应该比较 $a['meta'] > $b['meta']
  • 谢谢!成功了!

标签: php json sorting


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-03
    • 2013-04-06
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多