【问题标题】:SUM of the column in foreach array PHP not workingforeach 数组 PHP 中列的 SUM 不起作用
【发布时间】:2021-07-23 04:55:42
【问题描述】:

我已经创建了 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
        )
)

【问题讨论】:

  • 一个简单的方法是使用另一个查询“select sum(last_cost_rate) as totalsum from [tablename]”并先获取值,然后将此数字作为总键的值
  • 此代码不会运行,因为您在设置 last_costing 时缺少 $。
  • 这是错别字@NigelRen,否则它会给出输出
  • @KenLee 我不明白请帮助证明答案先生,请
  • 不要像这样嵌套查询。不要在循环内写prepare()。 $final['cost'] 不存在——$final 数组是关联数组的索引数组。不要修复此代码;把它扔掉。重构您的 sn-p 以使用 JOIN。

标签: php arrays foreach sum calculation


【解决方案1】:

构建数组后,只需使用 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 
      ) 
)

【讨论】:

  • 谢谢你的回答,但这段代码真的很难理解
  • 这有什么办法可以在我的代码中求和 $sum+=$last_costing - 这个解决方案也将解决我的问题
  • @Sidharth ,我找到了一种使用$sum+=$last_costing 来完成这项工作的方法,请参阅我修改后的答案(请注意,您的一些原始代码有问题,因此必须重写)-现在代码应该不会太难理解了
猜你喜欢
  • 1970-01-01
  • 2019-11-27
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
相关资源
最近更新 更多