如何对集合中的每条记录执行计算
Posted
技术标签:
【中文标题】如何对集合中的每条记录执行计算【英文标题】:how to perform calculations for each record in collection 【发布时间】:2022-01-11 17:12:40 【问题描述】:我有一组赌注,我需要计算 var $profit。 每条记录都有赌注和赔率。
这是我的收藏:
Illuminate\Database\Eloquent\Collection #1900 ▼
#items: array:4 [▼
0 => App\Models\Bet #1912 ▶
1 => App\Models\Bet #1906 ▶
2 => App\Models\Bet #1857 ▶
3 => App\Models\Bet #1882 ▶
]
和数组的属性:
#attributes: array:19 [▼
"id" => 4
"user_id" => 1
"status_id" => 1
"content" => "some text"
"sport" => "Basketball"
"competition" => "Premier league"
"start_date" => "2021-12-08"
"bookmaker_id" => 1
"team1" => "team one"
"team2" => "team two"
"selection_id" => 1
"tip" => "2,5"
"odds" => "5"
"unit_id" => 5
"created_at" => "2021-12-06 13:32:46"
"updated_at" => "2021-12-06 13:32:46"
"created_by" => 1
"updated_by" => null
"deleted_by" => null
]
如何在每个集合数组中进行计算? 例如计算利润(odds*unit_id(stake))
【问题讨论】:
使用集合map
方法。或者你可以使用accessors
你可以local scope
【参考方案1】:
这是我需要的东西:
$bets = array_map(function($item)
$item['won'] = number_format((double)$item['odds'] * (int)$item['unit_id'],3);
return $item;
, $bets);
【讨论】:
以上是关于如何对集合中的每条记录执行计算的主要内容,如果未能解决你的问题,请参考以下文章