php 如何用mysqli对多维数组中所有行的值求和?

idfiyjo8  于 2023-01-08  发布在  PHP
关注(0)|答案(2)|浏览(130)

你好,每一个我有小问题是有在mysqli和php
我有一个具有多行的表,并且我将在基于行的这些值的和的阵列中拾取一列值。

这里我将像这样放置图像array [0]+ array [0]+ array [0]=某个值
并且数组[n]+数组[n]+数组[n]=某个值可以打印出来
我的密码是

<?php  
$sql2="SELECT * FROM `purchase_data` where `project_id` ='$proid'";
$result2 = $conn->query($sql2);
$count2=$result2->num_rows;

if ($count2 > 0) {
    $x=1;
    $tot = 0;
    while ($pur_row = $result2->fetch_assoc()) {
        //$proid =$pur_row['pur_id']; 

        $category = $pur_row['pur_category'];
        $categories = explode(',',$category);
        $lenght = count($categories);
        //var_dump($category);

        $est_amou = $pur_row['pur_amount'];
        $est_amount = explode(',',$est_amou);
        var_dump($est_amount);
        //echo $ans_count = array_sum($est_amount);

        //echo $value = array_sum(array_column($est_amount,'pur_amount'));   

        $sum = array();
        foreach ($categories as $key => $sub_array) {
            echo $sub_array;
            foreach ($est_amount as $sub_key => $value) {

                echo $value;
                //If array key doesn't exists then create and initize first before we add a value.
                //Without this we will have an Undefined index error.
                if( ! array_key_exists($sub_key, $sum)) 
                    $sum[$sub_key] = 0;
                //Add Value
                $sum[$sub_key]+=$value;
            }
        }
        print_r($sum);

        for($i=0; $i< $lenght; $i++)
        { 
            $x++;
            $tot = $tot + $est_amount[$i];  
           // $balance = $estimation - $tot;
        } 
    } 
}  
?>

我的数据库如下所示

ou6hu8tu

ou6hu8tu1#

给定一个由逗号分隔的值组成的数组,这就是计算每个准列 * 单独 * 之和的方法。

$pur_amount = [
    "6250,2500,26000,12500,9000",
    "6250,2500,26000,12500,9000",
    "6250,2500,26000,12500,9000",
    "6250,2500,26000,12500,9000",
];

$pur_sum = [];
foreach($pur_amount as $string){
    foreach(explode(",", $string) as $id => $val){
        if(!array_key_exists($id, $pur_sum)){
            $pur_sum[$id] = 0;
        }
        $pur_sum[$id] += $val;
    }
}

var_dump($pur_sum);
hjzp0vay

hjzp0vay2#

MySQL查询可能是一个不错的选择,但您可以尝试将其作为PHP解决方案。

$arr = [
    [5,5,5,3,1],
    [6,4,2,3,5],
    [4,3,42,6,3]
];

var_dump(array_sum(array_column($arr, 0)));
var_dump(array_sum(array_column($arr, 1)));
var_dump(array_sum(array_column($arr, 2)));
var_dump(array_sum(array_column($arr, 3)));
var_dump(array_sum(array_column($arr, 4)));
int(15) int(12) int(49) int(12) int(9)

相关问题