数组值的添加不正确


Improper Addition of array values

我有一个这样的数组:

Array
(
    [0] => Array
        (
            [15] => Due
            [50] => Due
        )
    [1] => Array
        (
            [20] => Cancelled
            [30] => Due
        )
)

我想以表格格式在父数组的基础上显示到期金额的添加,如下所示:

Orders  DueAmount
  0       65     
  1       95     

我尝试过的代码:

<table border="1" cellpadding="5">
    <thead>
        <tr>
            <th>Orders</th>
            <th>DueAmount</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $tot = 0;
        for ($i=0; $i < count($ar); $i++) { // $ar is the parent array
            foreach ($ar[$i] as $key => $value) {
                if ($value === "Due") {
                    $amt = $tot += $key;
                    echo "<tr>";
                    echo "<td>".$i."</td>";
                    echo "<td>".$amt."</td>";
                    echo "</tr>";
                }
            }
        }
        ?>
    </tbody>
</table>

执行上述代码时,输出为:

Orders  DueAmount
  0       15
  0       65
  1       95

我该如何解决此问题?请帮帮我。

更新1

在vascowhile的评论之后:我得到以下输出

Orders  Due Amount
  0       15
  0       50
  1       30

只需将回声部分从前臂循环中移出即可:

for ($i=0; $i < count($ar); $i++) { // $ar is the parent array
    foreach ($ar[$i] as $key => $value) {
        if ($value === "Due") {
            $amt = $tot += $key;
        }
     }
     echo "<tr>";
     echo "<td>".$i."</td>";
     echo "<td>".$amt."</td>";
     echo "</tr>";
}

这个怎么样:

假设这是您的阵列:

$ar = array(
    array ( 
        15 => 'Due', 
        50 => 'Due' ),
    array ( 
        20 => 'Cancelled', 
        30 => 'Due' )
);

我将您的标记修改为:

<table border="1" cellpadding="5">
    <thead>
        <tr>
            <th>Orders</th>
            <th>DueAmount</th>
        </tr>
    </thead>
    <tbody>
    <?php
        // This variable will handle the due's
        $due = 0;
        foreach ($ar as $row_number => $data) {
            // I used the main key of your array as row counter, or if you don't trust this
            // you can just declare a counter outside the foreach 
            // and increment here. This will solve your first bug.
            $row_number++;
            foreach ($data as $amount => $header) {
                // Same as your logic, accumulate the due in a variable.
                // This will solve your second problem. 
                if ($header == 'Due') {
                    $due += $amount;   
                }
            }
            echo '<tr>';
                echo "<td>{$row_number}</td>";
                echo "<td>{$due}</td>";
            echo '<tr>';
        }
    ?>
    </tbody>
</table>