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

时间:2019-02-26 12:07:17

标签: php arrays mysqli multidimensional-array

你好,我有小问题的每个地方都在mysqli和php中

我有一个包含多行的表,我将根据行基于这些值的数组总和中提取一列值。

enter image description here

在这里,我将图像放置为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;
        } 
    } 
}  
?>

我的数据库看起来像这样

enter image description here

2 个答案:

答案 0 :(得分:1)

给出一个用逗号分隔的值的数组,这是您分别计算每个准列 的方式。

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

答案 1 :(得分:0)

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)