如何在php中求和数组值



编辑:现在这是我真正的问题。这是我的消息来源,但我的问题有点不同。如果数组键相同,则求和值。我的数组是:

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
        )
)
在上面的链接中,期望的结果是
Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

但是我想要的结果是

Array
(
    [one] => 12
    [two] => 10
    [three] => 7
)
    <?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
)

试试这个…

$sumArray = array();
foreach ($data as $key => $subArray) {

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

print_r($sumArray);

数组([1] => 12[二]=> 10[三]=> 7)

你所需要的只是一个嵌套的循环…

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

相关内容

  • 没有找到相关文章

最新更新