对数组值求和

时间:2014-06-16 13:44:01

标签: php arrays sum

我正在开发一个包含名称和分数列的排名表。还有一个额外的列可用于显示总计,这是所有分数的总和。

我使用array_sum并从组织值的$scores数组中提取信息。即使总和正常工作,它也只返回方括号中指定的名称的值。即:array_sum($scores["Mike"])为循环中的每一行打印37。另一方面,如果我只使用array_sum($scores),它会为循环中的每一行打印0!我需要将每个名称的正确总和加入到数组中。

这就是我所拥有的:

//scores values for each name
$scores = array(
    "Mike"    => array(04, 03, 00, 07, 04, 07, 00, 01, 00, 07, 04),
    "Kyle"    => array(07, 01, 00, 03, 04, 01, 00, 07, 03, 04, 04),
    "Johnny"  => array(07, 07, 00, 03, 00, 04, 00, 01, 01, 04, 03),
    "Will"    => array(03, 04, 00, 03, 04, 07, 00, 01, 00, 07, 04),
    "Vasques" => array(03, 01, 00, 03, 04, 07, 00, 01, 00, 07, 07)
);

//start loop for rows
foreach($scores as $key=>$value) {
  echo "<tr>";
  //column for the names
  echo "<td>$key</td>";
  //Total Column
  echo "<td class='total' align='center' valign='middle'>" . array_sum($scores["Mike"]) . "</td>";
  //loop for columns where the score should be displayed
  for($x=0; $x<count($value); $x++) {
    echo "<td class='games tip' align='center' valign='middle'>".sprintf('%02d', $value[$x])."</td>";
  }
  echo "</tr>";
}

它应该显示如下:

Mike    37   04  03  00  07  04  07  00  01  00  07  04
Kyle    34   07  01  00  03  04  01  00  07  03  04  04
Johnny  33   03  01  00  03  04  07  00  01  00  07  07

等...... 37,34和33是总和。

3 个答案:

答案 0 :(得分:0)

尝试将array_sum($scores["Mike"])更改为array_sum($scores[$key])并添加<table></table>代码

$scores = array(
    "Mike"    => array(04, 03, 00, 07, 04, 07, 00, 01, 00, 07, 04),
    "Kyle"    => array(07, 01, 00, 03, 04, 01, 00, 07, 03, 04, 04),
    "Johnny"  => array(07, 07, 00, 03, 00, 04, 00, 01, 01, 04, 03),
    "Will"    => array(03, 04, 00, 03, 04, 07, 00, 01, 00, 07, 04),
    "Vasques" => array(03, 01, 00, 03, 04, 07, 00, 01, 00, 07, 07)
);
echo '<table>';
//start loop for rows
foreach($scores as $key=>$value) {
  echo "<tr>";
  //column for the names
  echo "<td>$key</td>";
  //Total Column
  echo "<td class='total' align='center' valign='middle'>" . array_sum($scores[$key]) . "</td>";
  //loop for columns where the score should be displayed
  for($x=0; $x<count($value); $x++) {
    echo "<td class='games tip' align='center' valign='middle'>".sprintf('%02d', $value[$x])."</td>";
  }
  echo "</tr>";
}
echo '</table>';

输出: -

Mike    37  04  03  00  07  04  07  00  01  00  07  04
Kyle    34  07  01  00  03  04  01  00  07  03  04  04
Johnny  30  07  07  00  03  00  04  00  01  01  04  03
Will    33  03  04  00  03  04  07  00  01  00  07  04
Vasques 33  03  01  00  03  04  07  00  01  00  07  07

答案 1 :(得分:0)

更改此行:

echo "<td class='total' align='center' valign='middle'>" . array_sum($value) . "</td>";

您需要汇总$value var,而不是Mike密钥。

正如OP所质疑的那样,这可以用来命令数组。 在foreach循环之前添加它。

function cmp($a, $b) {
    return array_sum($b) - array_sum($a);
}
uasort($scores, "cmp");

答案 2 :(得分:0)

排序多维数组你可以在参数中使用带有SORT_ASC或SORT_DESC常量的“array_multisort”