如何在php中求和数组值

如何在php中求和数组值

问题描述:

EDIT : now this is my real problem. here is my source, but my question is a bit different. if array key is same then sum value. my array is:

Array
(
    [one] => Array
        (
            [gozhi] => 2
            [uzorong] => 1
            [ngangla] => 4
            [langthel] => 5
        )

    [two] => Array
        (
            [gozhi] => 5
            [uzorong] => 0
            [ngangla] => 3
            [langthel] => 2
        )

    [three] => Array
        (
            [gozhi] => 3
            [uzorong] => 0
            [ngangla] => 1
            [langthel] => 3
        )
)

in above link, desired result is

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

but my desired result is

Array
(
    [one] => 12
    [two] => 10
    [three] => 7
)

Try this...

$sumArray = array();

foreach ($data as $key => $subArray) {


    $sumArray[$key]=array_sum(array_values($subArray));
  }


print_r($sumArray);

Array ( [one] => 12 [two] => 10 [three] => 7 )

All you need is a nested loop...

$sumArray = array();
foreach ($outerArray as $innerArray)
{
    $sum = 0;
    foreach ($innerArray as $key => $value)
    {
        $sum += $value;
    }
    $sumArray[] = $sum;
}

print_r($sumArray);

That should give you what you're looking for.

    <?php

    $a = array(
            array
            (
                'gozhi' => 2,
                'uzorong' => 1,
                'ngangla' => 4,
                'langthel' => 5
            )

        ,array
            (
                'gozhi' => 5,
                'uzorong' => 0,
                'ngangla' => 3,
                'langthel' => 2
            )

        ,array
            (
                'gozhi' => 3,
                'uzorong' => 0,
                'ngangla' => 1,
                'langthel' => 3
            )
    );

    $sum_arr = array();

    foreach($a as $b)
    {
        if(is_array($b))
        {
            $sum = 0;
            foreach($b as $key=>$value)
            {
                $sum += $value;
            }
            $sum_arr[] = $sum;
        }
    }

    echo '<pre>';
    print_r($sum_arr);
    echo '</pre>';
    ?>
Output :
Array
(
    [0] => 12
    [1] => 10
    [2] => 7
)