Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improper Addition of array values

Tags:

arrays

php

I have an array like this:

Array
(
    [0] => Array
        (
            [15] => Due
            [50] => Due
        )

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

)

I want to display addition of the due amount on the parent array basis in the tabular format, like this:

Orders  DueAmount
  0       65     
  1       95     

The code that I have tried:

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

The above code when executed, gives the output as:

Orders  DueAmount
  0       15
  0       65
  1       95

How do I solve this ? Kindly help me out.

UPDATE 1:

After vascowhile's comment: I get the following output

Orders  Due Amount
  0       15
  0       50
  1       30
like image 217
Saiyan Prince Avatar asked Jun 09 '26 13:06

Saiyan Prince


1 Answers

Just move the echo'ing part out of your foreach loop :

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>";
}
like image 182
Clément Malet Avatar answered Jun 11 '26 02:06

Clément Malet