根据数组的对象对其进行排序';s值,该值包含时间戳


Sort array based on its object's value which contains a timestamp

首先我创建了两个不同的查询。

$first = first::where('id',$request->first_id)->select('name','created_at')->get();
$second = second::where('id', $request->second_id)->select('name','created_at')->get();

然后,我将得到的两个数组合并。

$data_combine = array_merge($first->toArray(), $second->toArray());

最后,我想根据它们的created_at值按升序对组合数组进行排序,例如"2016-05-06 16:43:46"。

使用Laravel Collection方法可以轻松完成此操作。与常规数组不同,使用Collection,您仍然可以访问Laravel在Models上提供的所有其他有用的集合方法。

您可以将数组合并到一个新集合中,然后对该集合进行排序。

collect(array_merge($first -> toArray(), $second -> toArray())) -> sortBy('created_at');

一种更流畅的写作方式也适用于

$first -> push($second) -> flatten() -> sortBy('created_at');

为了使其工作,created_at需要可见。如果尚未在模型的可见属性中定义(这样做是安全的),则需要首先添加该属性。否则,您需要循环初始集合并运行addVisible('created_at'),使其对当前结果可见。

$array = array_values(array_sort($data_combine , function ($value) {
    return $value['created_at'];
}));

您可以使用array_sort函数对合并后的数组进行排序。

https://laravel.com/docs/5.0/helpers#arrays

不需要使用toArray(),因为Collection有all()方法:

$combine = collect(array_merge($first->all(), $second->all()))->sortByDesc("created_at");

如果两个数组中只有一个元素,可以尝试:

$combine = collect([$first->first(), $second->first()])->sortByDesc("created_at");