数组值的不正确添加

时间:2015-03-06 09:53:58

标签: php arrays

我有一个这样的数组:

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

2 个答案:

答案 0 :(得分:2)

只需将回声部分移出foreach循环:

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>";
}

答案 1 :(得分:0)

这个怎么样:

让我们说这是你的阵列:

$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>