4

如果我在 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
            )

    )
4

3 回答 3

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');
于 2011-04-05T11:37:55.127 回答
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'];
}
于 2009-09-10T10:14:48.980 回答
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));
于 2017-03-06T06:40:02.943 回答