首页 > 解决方案 > 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
    ]

标签: phplaravellaravel-5

解决方案


我假设您想找到每个月的金额总和。

您必须遍历数组并根据年份和月份找到总和。

$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'];
}

这将为您提供一个数组,其中年月作为键,总金额作为相应的值。


推荐阅读