多维数组上的PHP Array_Sum

时间:2009-09-10 10:08:22

标签: php arrays sum array-sum

如果我在PHP中有一个多维数组,那么......

    [0] => Array
    (
        [url] => http://domain1.com
        [domain] => domain1.com
        [values] => Array
            (
                [character_length] => 25
                [word_count] => 7
            )

    )

    [1] => Array
    (
        [url] => http://domain2.com
        [domain] => domain2.com
        [values] => Array
            (
                [character_length] => 30
                [word_count] => 7

    )

如何将它们合并以生成......

    [0] => Array
    (
        [url] => *can be anything*
        [domain] => *can be anything*
        [values] => Array
            (
                [character_length] => 55
                [word_count] => 14
            )

    )

3 个答案:

答案 0 :(得分:7)

我认为没有任何内置函数可以让你对多维数组的值求和。但是,这是一种使用lambda样式函数的方法。

我们假设这是你的数组:

 [items] => Array
        (
            [0] => Array
                (
                    [ID] => 11
                    [barcode] => 234334
                    [manufacturer] => Dell
                    [model] => D630
                    [serial] => 324233
                    [current_value] => 1100.00
                )

            [1] => Array
                (
                    [ID] => 22
                    [barcode] => 323552
                    [manufacturer] => Dell
                    [model] => D630
                    [serial] => 234322
                    [current_value] => 1500.00
                )

        )

您可以创建一个可以将值传递给的函数:

$array_value_sum = create_function('$array,$key', '$total = 0; foreach($array as $row) $total = $total + $row[$key]; return $total;');

然后像这样使用它:

echo "Total Current Value" . $array_value_sum($obj['items'], 'current_value');

答案 1 :(得分:5)

只需对所有项目执行简单的foreach并对值进行求和:

$values = array(
    'character_length' => 0,
    'word_count'       => 0
);
foreach ($array as $item) {
    $values['character_length'] += $item['values']['character_length'];
    $values['word_count']       += $item['values']['word_count'];
}

答案 2 :(得分:0)

您可以使用array_sum()array_map()功能执行此操作,如下所示:

$totalCharacterLength = array_sum(array_map(function($item) { 
    return $item['values']['character_length']; 
}, $totalCharacterLength));

$totalWordCount = array_sum(array_map(function($item) { 
    return $item['values']['word_count']; 
}, $totalWordCount));