我让Eloquent返回了这个结果。已排序的effective_at升序
[
{
"id": 2200155,
"price": "0.07980",
"effective_at": "2020-10-01"
},
{
"id": 2218010,
"price": "0.07870",
"effective_at": "2020-10-06"
},
{
"id": 2256374,
"price": "0.07960",
"effective_at": "2020-10-15"
},
{
"id": 2273713,
"price": "0.08460",
"effective_at": "2020-10-19"
},
{
"id": 2300540,
"price": "0.08460",
"effective_at": "2020-10-26"
}
]我想要添加循环集合,并根据下一条记录的日期附加一个新的属性effective_end。如果没有下一条记录,则为Null
预期输出如下:-
[
{
"id": 2200155,
"price": "0.07980",
"effective_at": "2020-10-01",
"effective_end": "2020-10-05"
},
{
"id": 2218010,
"price": "0.07870",
"effective_at": "2020-10-06",
"effective_end": "2020-10-14"
},
{
"id": 2256374,
"price": "0.07960",
"effective_at": "2020-10-15",
"effective_end": "2020-10-18"
},
{
"id": 2273713,
"price": "0.08460",
"effective_at": "2020-10-19",
"effective_end": "2020-10-25"
},
{
"id": 2300540,
"price": "0.08460",
"effective_at": "2020-10-26",
"effective_end": null
}
]这就是我到目前为止所得到的。有没有更好的办法?
$results->transform(function ($item, $key) use ($results) {
$nextRecordDate = optional($results->get($key + 1))->effective_at;
$end = $nextRecordDate ? Carbon::parse($nextRecordDate)->subDay()->toDateString() : null;
$item->effective_end = $end;
return $item;
});发布于 2020-11-22 11:29:36
假设有说服力的结果是Models的集合,您可以通过这两种方法中的任何一种实现所需的结果
// Using object syntax
$results->map(function($item, $key) use($results) {
$nextStart = $results->get($key+1) ? $results->get($key+1)->effective_at : null;
$end = $nextStart ? \Illuminate\Support\Carbon::parse($nextStart)->subDay()->toDateString() : null;
$item->effective_end = $end;
return $item;
});
//Using arrayable access
$results->map(function($item, $key) use($results) {
$nextStart = isset($results[$key+1]) ? $results[$key+1]['effective_at'] : null;
$end = $nextStart ? \Illuminate\Support\Carbon::parse($nextStart)->subDay()->toDateString() : null;
$item['effective_end'] = $end;
return $item;
});https://stackoverflow.com/questions/64948572
复制相似问题