4

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
            )

    )
Mohammad
  • 21,175
  • 15
  • 55
  • 84
michael
  • 4,427
  • 6
  • 38
  • 57

3 Answers3

7

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');
Andy
  • 3,141
  • 3
  • 27
  • 22
5

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'];
}
Kermit
  • 33,827
  • 13
  • 85
  • 121
Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

You can do this using array_sum() and array_map() funtion like below:

$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));
Faisal
  • 4,591
  • 3
  • 40
  • 49
  • 1
    The best answer, except for the array_sum's second parameter should be the array variable. Still +1 for the method. – smozgur Feb 11 '23 at 23:36