简体   繁体   English

foreach多维数组php

[英]foreach multidimensional array php

from my question从我的问题

table layout - foreach 表格布局 - 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']如果我想显示总值,并出现在总计列中如何添加到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.只需适应您的需求,它就会解决您的问题,您就快到了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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