Sum Values ​​in a Multidimensional Array

I am experimenting with arrays in PHP and I am creating a fake environment in which the "team" entry is stored in the array.

$t1 = array (
        "basicInfo" => array (
            "The Sineps",
            "December 25, 2010",
            "lemonpole"
        ),
        "overallRecord" => array (
            0,
            0,
            0,
            0
        ),
        "overallSeasons" => array (
            "season1.cs" => array (0, 0, 0),
            "season2.cs" => array (0, 0, 0)
        ),
        "matches" => array (
            "season1.cs" => array (
                "week1" => array ("12", "3", "1"),
                "week2" => array ("8", "8" ,"0"),
                "week3" => array ("8", "8" ,"0")
            ),
            "season2.cs" => array (
                "week1" => array ("9", "2", "5"),
                "week2" => array ("12", "2" ,"2")
            )
        )
);

What I'm trying to achieve is to add all the wins , loss and draws , from each seasonal week to the corresponding week, So, for example, the sum of all weeks in $ t1 ["matches"] ["season1.cs"] will be added At $ t1 ["generalSeasons"] ["season1. CS"] . The result will leave:

"overallSeasons" => array (
    "season1.cs" => array (28, 19, 1),
    "season2.cs" => array (21, 4, 7)
),

, , , - for-loops foreach-loops: o... , , foreach ..; , , ! $t1 [ "matches" ] , , , draw, . , , , . , , , ... , !

!

+3
2

, , .

foreach ($t1['matches'] as $key=>$value){
   $wins = 0;
   $losses = 0;
   $draws = 0;
   foreach($value as $record){
      $wins   += $record[0];
      $losses += $record[1];
      $draws  += $record[2];
   }

   $t1['overallSeasons'][$key] = array($wins, $losses, $draws);
}
+2

:

foreach($t1['matches'] as $season => $season_array) {
        foreach($season_array as $week => $week_array) {
                for($i=0;$i<3;$i++) {
                        $t1['overallSeasons'][$season][$i] += $week_array[$i];
                }
        }
}

+7

Source: https://habr.com/ru/post/1781591/


All Articles