php - how to filter data in foreach
问题描述
here I want to add up by the month and year obtained from the API, so in 2019-12 he will add up all the amount of data that I got which is in 2019-1, the date format is yyyy-mm-dd and the date data is very irregular
0 => array:11 [
"id" => 1
"date" => array:5 [
"original" => "2019-11-29"
"day" => "Friday"
"date" => 29
"month" => 11
"year" => 2019
]
"amount" => 3754521
]
1 => array:11 [
"id" => 2
"date" => array:5 [
"original" => "2019-12-29"
"day" => "Friday"
"date" => 29
"month" => 12
"year" => 2019
]
"amount" => 20000
]
2 => array:11 [
"id" => 3
"date" => array:5 [
"original" => "2019-11-29"
"day" => "Friday"
"date" => 29
"month" => 11
"year" => 2019
]
"amount" => 500000
]
3 => array:11 [
"id" => 4
"date" => array:5 [
"original" => "2019-12-29"
"day" => "Friday"
"date" => 29
"month" => 12
"year" => 2019
]
"amount" => 200000
]
解决方案
我假设您想找到每个月的金额总和。
您必须遍历数组并根据年份和月份找到总和。
$data = // store your array here
$totals = [];
foreach($data as $element){
$year_month = $element['date']['year'] . '-' . $element['date']['month'];
$totals[$year_month] = isset($totals[$year_month]) ? $totals[$year_month] + $element['amount'] : $element['amount'];
}
这将为您提供一个数组,其中年月作为键,总金额作为相应的值。
推荐阅读
- javascript - 下拉过滤器在 React 中显示不正确的结果
- javascript - 从页面上的 div 内的内容脚本中注入 iframe 会在页面上的每个 iframe 中注入 src html
- c - 为linux内核中的struct数组分配内存并得到奇怪的输出od structs ids
- c# - 在一个 TextBox Asp.Net Mvc 中搜索多个项目
- swift - Swift:TableView didSelectRowAt 仅针对某些行触发?
- javascript - React redux,数组状态不更新
- memory-management - 具有 CPU 和内存可视化的循环内存调度
- go - 评估期望值为 Go 接口的 hcl.Expression
- java - 注入的类是否必须具有特定于弹簧的注释?
- python - Dash 中的 Windrose (Barpolar) 未更新