如何在php中求和数组值

时间:2015-08-08 06:38:49

标签: php arrays multidimensional-array

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

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
)

3 个答案:

答案 0 :(得分:3)

eartman_designer_registration_register:
    path: /
    defaults: { _controller: "FOSUserBundle:Registration:register" }

eartman_designer_registration_check_email:
    path: /check-email
    defaults: { _controller: "FOSUserBundle:Registration:checkEmail" }
    methods: "GET"

eartman_designer_registration_confirm:
    path: /confirm/{token}
    defaults: { _controller: "FOSUserBundle:Registration:confirm"}
    methods: "GET"

eartman_designer_registration_confirmed:
    path: /confirmed
    defaults: { _controller: "FOSUserBundle:Registration:confirmed" }
    methods: "GET"

答案 1 :(得分:2)

试试这个......

$sumArray = array();

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


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


print_r($sumArray);

阵 (     [one] => 12     [two] => 10     [三] => 7 )

答案 2 :(得分:0)

您只需要一个嵌套循环......

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

print_r($sumArray);

这应该可以为您提供所需的信息。