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

SUM of the column in foreach array PHP not working

我创建了 foreach 函数并在该函数内部尝试计算列的总和。 我已经阅读了 Whosebug 或 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 块来替换所有总计:

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

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