0

I have the following 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"
    }

And I would like to rearange it based on the likes from heighst to lowest so the result will be :

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

How can I rearange it in php ?

Alison R.
  • 4,204
  • 28
  • 33
gilm501
  • 151
  • 1
  • 2
  • 8
  • 2
    covert this json to array json_decode(json,true); use some array sorting function sort it and then re-create the json. – Abhik Chakraborty Apr 14 '14 at 14:40
  • possible duplicate of [Sort Multi-dimensional Array by Value](http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value) – Amal Murali Apr 14 '14 at 14:42

2 Answers2

5

json_decode / json_encode and usort:

$array = json_decode($json_string, TRUE);

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

echo json_encode($array, JSON_PRETTY_PRINT);

Demo

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Steve
  • 20,703
  • 5
  • 41
  • 67
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);
dave
  • 62,300
  • 5
  • 72
  • 93