首页 文章

如何使用php计算多个数据库行中数组数组的总和?

提问于
浏览 1152
1

我需要计算多行中MySQL数据库行列中存在的元素数量,然后将它们全部加在一起 . 这是我用来计算数组元素数量的代码(用逗号分隔的数字):

$result = substr_count($count_fetch['micro_analysis'], ",") + 1;

但现在我需要为每一行执行此操作,这可能会因查询而异 . 我需要将每行的 $result 添加到一起以获得所有行的最终总和 . 我使用了以下代码,但是我得到的值不正确,有人可以指点我正确的方向吗?

$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";

      $count_query = mysqli_query($conn, $sql);
      $count_fetch = mysqli_fetch_assoc($count_query);

      foreach ($count_fetch as $row) {
         $result = substr_count($count_fetch['micro_analysis'], ",") + 1;
         $end_result += $result;

      }

      echo $end_result;

2 回答

  • 1

    用以下代码替换您的代码:

    $sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
    
          $count_query = mysqli_query($conn, $sql);
          $count_fetch = mysqli_fetch_assoc($count_query);
          $end_result=0;//initialize variable to 0
          foreach ($count_fetch as $k => $row) {
             if($k == 'micro_analysis'){
               $result = substr_count($row, ",") + 1; //change over here
               $end_result += $result;
             }
          }
    
          echo $end_result;
    
  • 1

    您只是获取1行然后尝试计算该行,而是需要循环遍历行并在其中添加字段...

    $sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
    
      $end_result = 0;
      $count_query = mysqli_query($conn, $sql);
      while( $row = mysqli_fetch_assoc($count_query)) {
         $end_result += substr_count($row['micro_analysis'], ",") + 1;
      }
    
      echo $end_result;
    

相关问题