简体   繁体   中英

foreach multidimensional array php

from my question

table layout - foreach

this is source code

<table>

<tr>
<th>No</th>
<th>Name</th>
<th>Month</th>
<th>Total</th>
</tr>

$no=1;
    while($row = mysqli_fetch_assoc($sql2))
    {
        $CATEGORY[$row['NAME']][]=$row['MONTH'];
    }
    $old = 0;

    foreach($CATEGORY as $key => $CATEGORY)
    {
        foreach($CATEGORY as $CODE)
        { 
        echo "<tr>";

           if($old == 1)
           {
              echo "<td></td>
              <td></td>";
           }
           else
           {
              echo "<td>".$no."</td>
              <td>".$key."</td>";
              $old = 1;
          }

        echo "<td>";
        echo $CODE."<br>";
        echo "</td><td></td></tr>";
        }
        $old = 0;
        $no=$no+1;
    }
    echo '</table>';

If I want to show total value,and appearing in the column total how to add to the array in foreach ex: $row['TOTAL']

I get it now.

<table>

 <tr>
  <th>No</th>
  <th>Name</th>
  <th>Month</th>
  <th>Total</th>
 </tr>

 <?php

    while($row = mysqli_fetch_assoc($sql2))
    {
      $CATEGORY[]=['id_month' => $row['id_month'], 'name' => $row['name'], 'month' => $row['month'], 'total' => $row['total'];
    }

    foreach($CATEGORY as $key => $val) {
       echo '<tr>';
        echo '<td>'.$val['id_month'].'</td>';
        echo '<td>'.$val['name'].'</td>';
        echo '<td>'.$val['month'].'</td>';
        echo '<td>'.$val['total'].'</td>';
       echo '</tr>';
    }
 ?>
 </table>

You need to loop through the array to calculate total, each iteration you add the value to the initial total variable.

$data = [
   ['id' => 1,'cost' => 10],
   ['id' => 1,'cost' => 10],
   ['id' => 1,'cost' => 10]
];
$total = 0;
foreach($data as $key => $value){
 $total +=$value['cost'];

}
echo $total; // 30

This how you would calculate the total or you could also do it in your query. Just adapt to your needs and it should solve your problem, you are almost there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM