Newbie 123
Newbie 123

Reputation: 274

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
    ]

Upvotes: 1

Views: 267

Answers (1)

Ahmed Shefeer
Ahmed Shefeer

Reputation: 394

I assume you want to find the sum of amounts for each month.

You have to iterate over the array and find the sums based on year and month.

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

This will give you an array with year-month as keys and the total amount as the corresponding values.

Upvotes: 1

Related Questions