phparraysmultidimensional-arraysumarray-sum

Sum columnar data in the 3rd level of a multidimensional array


If I have a multi dimensional array in PHP like so...

    [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

    )

How can I merge them to produce....

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

    )

Solution

  • Just do a simple foreach on all items and sum the values:

    $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'];
    }