PHP 二维数组与表格的总和


php two dimensional array with sums to table

im 在 serach 中表示使用和数组的通用代码段

$arr[$key1][$key2] = $value;

输出应该是这样的,其中"SUM"不是数组的一部分。

     | 1st key2 | 2nd key2 | 3rd key2 | SUM
1st key1  |       10 |       10 |       10 |  30
2nd key1  |       10 |       10 |       10 |  30
3rd key1  |       10 |       10 |       10 |  30
SUM       |       30 |       30 |       30 |  90

所以我启动一个输出,看看我能走多远:

echo '<table width="100%"><thead>';
foreach($arr as $linekey => $line)
{
    echo '<tr>';
    echo '<th align="center">';
    echo '</th>';
    foreach($line as $key => $value)
    {
        echo '<th align="center">';
        echo $key;
        echo '</th>';
    }
    echo '<th align="center">';
    echo 'SUM';   //adding the SUM column
    echo '</th>';
    echo '</tr>';
    break;
}
echo '</thead><tbody>';
foreach($arr as $key1 => $value1)
{ echo '<tr>';
     echo'<td>'.$key1.'</td>';
     $sumRow = 0; //reset sumRow
    foreach($arr[$key1] as $key2 => $value2)
    {
         echo'<td>'.round($arr[$key1][$key2],0).'</td>';      
         $sumRow += $arr[$key1][$key2]; //summing up rows
         $sumAll += $arr[$key1][$key2]; //summing up everything
         $sumCol += $arr[$key1][$key2]; //where should be this?
    }
    echo'<td>'.round($sumRow,0).'</td>'; //echo $sumRow
    echo '</tr>';
}
echo '</tbody></table>';

这个 alaredy 有效,但我不确定在哪里对列求和

您应该使用数组$sumCol来收集列总和:

$sumCol[$key2] += $arr[$key1][$key2];

它的大小应为列数。

如果没有数组,

您就无法在一个循环中执行此操作,因为您在内部循环访问列索引,因此您可以在一个临时变量(没有数组)中仅收集sumRow

然后,在最后:

echo '<tr><td>SUM</td>';
    foreach($sumCol as $key2 => $value2)
    {
        echo'<td>'.round($sumCol[$key2],0).'</td>'; //echo $sumCol
    }
echo '</tr>';
echo '</tbody></table>';

另一种方法是定义第二个循环,首先迭代列,然后在内部迭代行。