donglu2008 2017-05-18 19:28
浏览 94
已采纳

Laravel - 如何按不同键的时间戳值对数组对象进行排序?

I have this array of objects from a Laravel merged collection, accessed like this, $collection->values()->all(), which returns the following:

 [
  {
    "id": "1",
    "type": "Teacher",
    "created_at": "2017-05-11 18:00:00"
  },
  {
    "id": "2",
    "type": "Student"
    "created_at": "2017-05-11 15:00:00"
  },
  {
    "id": "3",
    "type": "Course",
    "data": {
       "title: "PHP",
       "created_at": "2017-05-11 16:00:00"
    }
  }
]

I am trying to sort the order by the created_at field, so it looks like this:

 [
  {
    "id": "1",
    "type": "Teacher",
    "created_at": "2017-05-11 18:00:00"
  },
  {
    "id": "3",
    "type": "Course",
    "data": {
       "title: "PHP",
       "created_at": "2017-05-11 16:00:00"
    }
  },
  {
    "id": "2",
    "type": "Student"
    "created_at": "2017-05-11 15:00:00"
  }
]

The issue is that created_at is in two locations, sometimes it's under created_at and other times it's under data.created_at.

  • 写回答

1条回答 默认 最新

  • douyicao2199 2017-05-18 19:36
    关注

    I think you can use the sortByDescfunction:

    $sorted = $collection->sortByDesc(function ($element) {
        return $element->data ? $element->data->created_at : $element->created_at;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决