php - 如何对多维数组求和

时间:2018-03-14 04:35:47

标签: php arrays multidimensional-array

我的数据如下:

Array(
        [A] => Array
            (
                [AA] => 10
            )

        [B] => Array
            (
                [BA] => 5
                [BB] => 1
                [BC] => -2
            )

        [C] => Array
            (
                [CA] => 3
                [CB] => 0
            )
    )

我想将第二个元素的值加到我的数组(BA,BB,BC等),如下所示:

    Array(
        [A] => 10        
        [B] => 4
        [C] => 3
    )

我尝试用foreach(我使用php作为我的平台),但结果是错误的,有人可以给我解释和逻辑来解决这个问题吗?感谢

3 个答案:

答案 0 :(得分:3)

您可以循环播放数组并使用array_sum

$arr = array(
    "A" => array
        (
            "AA" => 10,
        ),

    "B" => array
        (
            "BA" => 5,
            "BB" => 1,
            "BC" => -2
        ),

    "C" => array
        (
            "CA" => 3,
            "CB" => 0
        )
);

$result = array();
foreach( $arr as $key => $val ){
    $result[$key] = array_sum ( $val );
}

echo "<pre>";
print_r( $result );
echo "</pre>";

这将导致:

Array
(
    [A] => 10
    [B] => 4
    [C] => 3
)

Doc:http://php.net/manual/en/function.array-sum.php

答案 1 :(得分:1)

这应该适用于您的示例之类的数组:

 $arr = array(
    "A" => array
        (
            "AA" => 10,
        ),

    "B" => array
        (
            "BA" => 5,
            "BB" => 1,
            "BC" => -2
        ),

    "C" => array
        (
            "CA" => 3,
            "CB" => 0
        )
);
$res = array();
foreach($arr as $key => $value) {
        foreach($value as  $number) {
            (!isset($res[$key])) ?
                $res[$key] = $number :
                $res[$key] += $number;
        }
    }



echo "<pre>";
print_r( $res );
echo "</pre>";

这可以在不使用内置函数的情况下工作。

答案 2 :(得分:0)

如果您想要总和列

<?php
$array = array
    (
      "A"=>array
        (
"AA" => 10,
        ),
      "B"=>array
        (
            "BA" => 5,
            "BB" => 1,
            "BC" => -2
        ),
      "C"=>array
        (
            "CA" => 3,
            "CB" => 0
         )
        );

foreach ($array as $key=>$value)
{
$mehrdad[]=$key;
}
foreach ($mehrdad as $key1=>$value1)
{
    $arrays=$array[$value1];
foreach ($arrays as $key2=>$value2)
{

$mehrdadi[]=$key2;
}

}
$mehrdadend=array_unique($mehrdadi);
$mehrdadis = array();
foreach ($mehrdadend as $key3=>$value3)
{
$sum=array_sum(array_column($array, $value3));

$mehrdadis[$value3] = $sum;
}
print_r($mehrdadis);
?>

<强>结果

Array
(
    [AA] => 10
    [BA] => 5
    [BB] => 1
    [BC] => -2
    [CA] => 3
    [CB] => 0
)