Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array_Sum on multi dimensional 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
            )

    )
like image 835
michael Avatar asked Dec 17 '22 06:12

michael


2 Answers

I don't think there's any built-in function that would let you sum the values of a multidimensional array. However, here's a way of doing it using a lambda-style function.

Let's suppose this is your array:

 [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
                )

        )

You could create a function that you could pass values to:

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

And then use it like so:

echo "Total Current Value" . $array_value_sum($obj['items'], 'current_value');
like image 84
Andy Avatar answered Mar 09 '23 15:03

Andy


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'];
}
like image 45
Gumbo Avatar answered Mar 09 '23 15:03

Gumbo