如何在Laravel中对JSON对象进行排序 [英] how to sort a json object in laravel

查看:173
本文介绍了如何在Laravel中对JSON对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下响应,如何根据距离进行排序

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
      }
  ]
}

我尝试了usort,但我没有成功. 我也在此处尝试过此答案,但它似乎与我需要一个

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

推荐答案

在纯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);

这篇关于如何在Laravel中对JSON对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆