多维数组中的和值

时间:2010-12-22 05:35:42

标签: php arrays multidimensional-array foreach for-loop

我正在使用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 [“匹配”] [“season1.cs”] 中所有周的总和将添加到 $ t1 [“overallSeasons”] [“season1。 CS“] 即可。结果将离开:

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

我在过去一小时内尝试自己解决这个问题,而我所获得的只是对 for-loops foreach-loops 的更多了解:o ...所以我认为我现在已经掌握了基础知识,例如使用 foreach 循环等等;但是,我仍然相当新,所以请耐心等待!我可以让循环指向 $ t1 [“匹配”] 键并经历每个赛季,但我似乎无法弄清楚如何添加所有胜利,损失绘制。就目前而言,我只是在寻找有关整体季节总和的答案,因为一旦我弄清楚如何实现这一点,我就可以在那里工作。任何帮助将不胜感激,但请尽量为我保持简单...或者相应地评论代码!

谢谢!

2 个答案:

答案 0 :(得分: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];
                }
        }
}

See it

答案 1 :(得分: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);
}