$users = User:all();
//User:all() is based on the laravel eloquent model , it's just similar to 'select * from user' query
$total_spend_amount = 0;
foreach($users as $user)
{
$total_spend_amount += $user->spend_amount;
}
echo "Total spend amount :".$total_spend_amount;
//Note: In this simple example i just want to sum of all the spend_amount
以上只是一個簡單的例子,我如何做一些算法的結果查詢沒有循環/ foreach在PHP?我如何執行一個操作結果mysql查詢結果沒有循環/ foreach
User::all()->sum('spend_amount'); // this is the answer below and this is correct
//but how about if i want the 'specific algorithm' to be performed on the resulted query instead of sum?
但怎麼樣,如果我想在「特定算法」要對查詢結果,而不是總和進行?
你只想要花錢的總和? –
@GauravGupta不只是總結,如果可能的話,我想要自定義的一個。 –
我從一塊肥皂中不知道Laravel,但是你不想爲你的收藏套用一個'reduce'處理程序嗎? https://laravel.com/docs/5.4/collections#method-reduce –