多维数组求和

3

我正在尝试使用PHP中的数组,并且正在设置一个虚拟环境,其中“团队”的记录存储在数组中。

$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")
            )
        )
);

我想要实现的目标是将每个赛季的每个星期的所有胜利、失败和平局相加,然后加到它们各自的星期中。例如,$t1["matches"]["season1.cs"] 中所有星期的总和将添加到 $t1["overallSeasons"]["season1.cs"] 中。结果如下:
"overallSeasons" => array (
    "season1.cs" => array (28, 19, 1),
    "season2.cs" => array (21, 4, 7)
),

我一个人尝试了一个小时,目前我只学会了一些关于for循环和foreach循环的知识,所以我认为我已经掌握了基础,例如使用foreach循环等等; 但是,我还是比较新手,所以请耐心点!我可以让循环指向$t1["matches"]的键,并遍历每个赛季,但我似乎无法弄清楚如何添加每个单独星期的所有胜利、失败和平局。目前,我只想寻找关于整个赛季总和的答案,因为一旦我弄清楚如何实现这一点,我就可以从那里开始工作。非常感谢任何帮助,但请尽量对我简化...或者根据代码进行评论!
谢谢!
2个回答

7

试试这个:

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

点击查看


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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接