how to sort a json object in laravel

て烟熏妆下的殇ゞ 提交于 2020-12-12 12:28:05

问题


i have the following response, how to sort it depending on the distnace

{
  "Message": "Done.",
  "Status": true,
  "InnerData": [
      {
         "id": 66,
         "name": "tito",
         "distance": 74,
      },
      {
         "id": 67,
         "name": "liver pool",
         "distance": 83
      },
      {
         "id": 67,
         "name": "Text",
         "distance": 72
      }
  ]
}

i tried the usort but i didn't make it. i also tried this answer here but it seems to be different than the one i need


回答1:


In pure PHP 7

<?php

$json = '{
  "Message": "Done.",
  "Status": true,
  "InnerData": [
      {
         "id": 66,
         "name": "tito",
         "distance": 74
      },
      {
         "id": 67,
         "name": "liver pool",
         "distance": 83
      },
      {
         "id": 67,
         "name": "Text",
         "distance": 72
      }
  ]
}';
$array = json_decode($json, true);
usort($array['InnerData'], function($a, $b) {
    return $a['distance'] <=> $b['distance'];
});

print_r($array);



回答2:


As @hdifen suggested, if you're using Laravel it's a breeze to do this.

$json = '{
  "Message": "Done.",
  "Status": true,
  "InnerData": [
      {
         "id": 66,
         "name": "tito",
         "distance": 74
      },
      {
         "id": 67,
         "name": "liver pool",
         "distance": 83
      },
      {
         "id": 67,
         "name": "Text",
         "distance": 72
      }
  ]
}';

$data = json_decode($json, true);

$data['InnerData'] = collect($data['InnerData'])->sortBy('distance', SORT_REGULAR, true);

$encoded = json_encode($data);

echo $encoded;

Output:

{  
   "Message":"Done.",
   "Status":true,
   "InnerData":{  
      "1":{  
         "id":67,
         "name":"liver pool",
         "distance":83
      },
      "0":{  
         "id":66,
         "name":"tito",
         "distance":74
      },
      "2":{  
         "id":67,
         "name":"Text",
         "distance":72
      }
   }
}



回答3:


Json is mainly used as a common format for sending data.

In Laravel you can convert a json object to a php array easily by using json_decode().

$phpArray = json_decode($json);

From here you can convert it to a collection to take advantage of laravels collection functions.

$laravelArray = collect($phpArray);

After this take a look at https://laravel.com/docs/5.5/collections to do sort/filter or do whatever you want to the array.



来源:https://stackoverflow.com/questions/50450667/how-to-sort-a-json-object-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!