【问题标题】:Sum Values in Multidimensional Array多维数组中的和值
【发布时间】:2011-05-29 05:36:24
【问题描述】:

我正在用 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-loopsforeach-loops 有了更多的了解:o ...所以我想我现在已经掌握了基础知识,例如使用 foreach 循环等等;但是,我对此还是很陌生,所以请耐心等待!我可以让循环指向 $t1["matches"] 键并遍历每个赛季,但我似乎无法弄清楚如何添加所有 wins损失平局,每个星期。目前,我只是在寻找有关整个赛季总和的答案,因为一旦我弄清楚如何实现这一目标,我就可以从那里开始工作。任何帮助将不胜感激,但请尽量让我保持简单...或相应地评论代码!

谢谢!

【问题讨论】:

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


    【解决方案1】:

    试试这个:

    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

    【讨论】:

      【解决方案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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        • 1970-01-01
        相关资源
        最近更新 更多