PHP从最高到最低排序JSON

时间:2014-04-14 14:38:20

标签: php json sorting

我有以下json:

     {
    "ID":"4",
    "name":"Gil",
    "likes":0,
    "Dec":"A Man"
    },
    {
   "ID":"3",
    "name":"Yoni",
    "likes":3,
    "Dec":"A child"
    },
    {
    "ID":"6",
    "name":"Roni",
    "likes":1,
    "Dec":"A woman"
    }

我想根据喜欢从最高到最低重新排列它,结果将是:

{
        "ID":"5",
        "name":"Roni",
        "likes":6,
        "Dec":"A woman"
        } ,  
   {
       "ID":"3",
        "name":"Yoni",
        "likes":3,
        "Dec":"A child"
        },

 {
        "ID":"4",
        "name":"Gil",
        "likes":0,
        "Dec":"A Man"
        }

如何在php中重新排列?

2 个答案:

答案 0 :(得分:5)

json_decode / json_encodeusort

$array = json_decode($json_string, TRUE);

usort($array, function($a, $b) {
    return $a['likes'] - $b['likes'];
});

echo json_encode($array, JSON_PRETTY_PRINT);

Demo

答案 1 :(得分:1)

$json = '[{
  "ID":"4",
  "name":"Gil",
  "likes":0,
  "Dec":"A Man"
},
{
  "ID":"3",
  "name":"Yoni",
  "likes":3,
  "Dec":"A child"
},
{
  "ID":"6",
  "name":"Roni",
  "likes":1,
  "Dec":"A woman"
}]';

$json_arr = json_decode($json, true);
usort(
  $json_arr, 
  function($a, $b) { 
    if ($a['likes'] == $b['likes']) {
      return 0;
    }
    return ($a['likes'] > $b['likes']) ? -1 : 1;
});
$json = json_encode($json_arr);