沃梦达 / 编程问答 / php问题 / 正文

对多个数组中的列值求和

Sum column values from multiple arrays(对多个数组中的列值求和)

本文介绍了对多个数组中的列值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有动态名称的数组。我的数组可以大于3,取决于数组变量,并且数组变量应该是唯一的

$loopThrice = 3;
$getSum = 0;
$total = array();

$array0 = array(5, 10, 15, 20, 25, 30);
$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(2, 6, 8, 10, 12, 14);

for($a=0; $a < $loopThrice; $a++){ // loop 3x to get unique array name
    foreach (${'array'.$a} as $key => $value) { // $array0, $array1, $array2,  
        //Right here is my problem, I'm not sure if this the correct way to get the sum of $array0,1,2
        
        //get the sum of array0,1,2 -- newarray(8, 18, 26, 34, 42, 50)
        $getSum += 
            //store newarray
            array_push($total, $getSum);     
    }
}

我需要获得如下输出:

Array ( 
    [0] => 8
    [1] => 18 
    [2] => 26 
    [3] => 34 
    [4] => 43 
    [5] => 50 
)

推荐答案

为什么不使用多维数组?

$array = array(); // hungarian notation
$array[] = array(5, 10, 15, 20, 25, 30);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10, 12, 14);

在本例中,您将拥有一个数组数组:

Array
(
[0] => Array
    (
        [0] => 5
        [1] => 10
        [2] => 15
        [3] => 20
        [4] => 25
        [5] => 30
    )

[1] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
        [5] => 6
    )

[2] => Array
    (
        [0] => 2
        [1] => 6
        [2] => 8
        [3] => 10
        [4] => 12
        [5] => 14
    )
)

您可以使用嵌套的for循环:

$sumArray = array();
$arrayCount = count($array);
$elementCount = 0;

foreach($array as $subarray)
{
    $count = count($subarray);
    $elementCount = $elementCount < $count ? $count : $elementCount;
}

for($i = 0; $i < $elementCount; $i++)
{
    $sumArray[$i] = 0;

    for($j = 0; $j < $arrayCount; $j++)
    {
        $sumArray[$i] += $array[$j][$i];
    }
}

print_r($sumArray);

输出为

Array
(
    [0] => 8
    [1] => 18
    [2] => 26
    [3] => 34
    [4] => 42
    [5] => 50
)
现在,如果您有一个不成比例的子数组(即每个子数组中的元素计数不同),您仍然会得到某种结果,因为丢失的元素将被假定为0。因此,输入:

$array = array(); // hungarian notation
$array[] = array(5, 10, 15, 20, 25);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10);

您仍将获得结果:

Array
(
    [0] => 8
    [1] => 18
    [2] => 26
    [3] => 34
    [4] => 30
    [5] => 6
)

这篇关于对多个数组中的列值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:对多个数组中的列值求和

基础教程推荐