我如何遍历集合中的所有项目以获得对象中某个键的总和?
softAssert.asserEquals(actual, expected, "Your customized message")
在addMeta()中,我要包括所有项目-> price->值的'total_sum'。
当我这样添加时:
$data = fractal()
->collection($items, new ItemTransformer())
->paginateWith(new IlluminatePaginatorAdapter($paginator))
->addMeta([
'from' => $from->toDateString(),
'till' => $till->toDateString(),
])
->toArray();
它不会遍历集合,而是遍历item表中的所有值。
答案 0 :(得分:0)
也许这行得通吗?
$sum = 0;
$totalPrice = $items->price;
foreach($totalPrice as $key=>$value){
if(isset($value->value))
$sum += $value->value;
}
echo $sum;
答案 1 :(得分:0)
我目前的做法:
$seller = $this->sellerRepository->findOrFail($id);
$query = $seller->items()->whereHas('baseItem');
$totalSum = $query->get()->sum(function ($item) {
return $item->baseItem->price->value;
});
$paginator = $query->paginate($request->get('_perPage', $this->sellerRepository->getPerPage()));
$items = $paginator->items();
$data = fractal()
->collection($items, new ItemTransformer())
->paginateWith(new IlluminatePaginatorAdapter($paginator))
->addMeta([
'from' => $from->toDateString(),
'till' => $till->toDateString(),
'total_sum' => $totalSum,
'page_sum' => collect($items)->sum(function ($item) {
return $item->baseItem->price->value;
}),
])
->toArray();
return response()->json($data);
}
感谢您的提示。