微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

foreach 数组 PHP 中列的总和不起作用

如何解决foreach 数组 PHP 中列的总和不起作用

我已经创建了 foreach 函数,并在该函数内部尝试计算列的总和。 我已经阅读了 StackOverflow 或 google 上的所有相关主题,但是我尝试了 3 天,但无法得到答案并解决了我的问题。 请帮助我,我如何计算列,我想对所有 [cost] 求和并显示[total] 中。

请帮帮我。

table = table1
    ID | key    | p_name
    ---------------------
    1  | 123456 | A
    2  | 145236 | B

table = table2
    ID | column | key
    ---------------------
    1  | 10     | 123456
    2  | 5      | 123456
    3  | 20     | 145236
    4  | 30     | 145236

$stmt = $con->prepare("SELECT * FROM `table1`");
$stmt->execute();
$result = $stmt->fetchAll();
$final = [];
foreach ($result as $data => $value) {
    $stmt01 = $con->prepare("SELECT * FROM `table1`");
    $stmt01->execute();
    if($stmt01->rowCount() > 0) {
        while($result001 = $stmt01->fetch(PDO::FETCH_ASSOC)) {
            $name = $result001['p_name'];

            $sql = $con->prepare("SELECT `ID`,SUM(`column`) AS `last_cost_rate`,`key` FROM `table2` WHERE `key` = :key AND `ID` = (SELECT MAX(`ID`) FROM `table2` WHERE `key` = :key)");
            $sql->execute(array(':key' => $value['key']));
            $sum = 0;
            while($sqlvalue001 = $sql->fetch(PDO::FETCH_ASSOC)) {
                $last_costing = $sqlvalue001['last_cost_rate'];
                $sum+=$last_costing
            }

        }
    }

    
    $final[] = [
        'name' => $name,'total' => $sum
    ];              
}

输出

Array
(
    [0] => Array
        (
            [product] => A
            [total] => 5
        )

    [1] => Array
        (
            [product] => B
            [total] => 30
        )
)

解决方法

构建数组后,只需使用 foreach 块替换所有 sumtotal :

因此您可以继续使用以下内容:

$sum += $last_costing;

然后使用以下 foreach 来填充数据:

foreach ($final as &$value) {
$value['sumtotal'] = $sum;
}

所以,代码(完全工作)是:

<?php
// Note: put your real username/password in the following line :

$conn = new mysqli("localhost","user","password","dbname");

$sql="select table1.p_name,table1.`key`,table2.`column` from table1,table2 where table1.`key`=table2.`key` order by table1.id,table2.id desc";

$final = [];
$sum=0;
$stmt = $conn->prepare($sql); 
$stmt->execute();
$result = $stmt->get_result();
$opname="";
    while ($c = $result->fetch_assoc()) {
      if ($opname!=$c["p_name"]) {
          $opname=$c["p_name"];  


      $last_costing=$c["column"];

      $sum += $last_costing;

         $final[] = [
        'product' => $c["p_name"],'total' => $c["column"],'sumtotal' => 0
         ];      
      }
  }

foreach ($final as &$value) {
$value['sumtotal'] = $sum;
}

print_r($final);
?>

结果是:

Array 
( 
    [0] => Array 
      ( 
      [product] => A 
      [total] => 5 
      [sumtotal] => 35 
      ) 
    [1] => Array 
      ( 
       [product] => B 
       [total] => 30 
       [sumtotal] => 35 
      ) 
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。