Viewed   91 times

Need a little help here with summing up arrays inside a multi dimensional php array

Eg Multidimensional array

Array
(
    [0] => Array
        (
            [0] => 30
            [1] => 5
            [2] => 6
            [3] => 7
            [4] => 8
            [5] => 9
            [6] => 2
            [7] => 5
        )

    [1] => Array
        (
            [0] => 50
            [1] => 4
            [2] => 8
            [3] => 4
            [4] => 4
            [5] => 6
            [6] => 9
            [7] => 2
        )
)

I want to have a result array that will be holding sum of both these arrays like this

Array
(
    [0] => 80
    [1] => 9
    [2] => 14
    [3] => 11
    [4] => 12
    [5] => 15
    [6] => 11
    [7] => 7
)

Any help will be greatly appreciated

Thanks!

 Answers

2

This should work for arrays like the one of your example ($arr is an array like the one in your example, I haven't defined it here for simplicity's sake):

$res = array();
foreach($arr as $value) {
    foreach($value as $key => $number) {
        (!isset($res[$key])) ?
            $res[$key] = $number :
            $res[$key] += $number;
    }
}

print_r($res);
Friday, September 30, 2022
 
2

Try below code:

<?php

$arr = array(
        array('city' => 'NewYork', 'cash' => '1000'),
        array('city' => 'Philadelphia', 'cash' => '2300'),
        array('city' => 'NewYork', 'cash' => '2000'),
    );

$newarray = array();
foreach($arr as $ar)
{
    foreach($ar as $k => $v)
    {
        if(array_key_exists($v, $newarray))
            $newarray[$v]['cash'] = $newarray[$v]['cash'] + $ar['cash'];
        else if($k == 'city')
            $newarray[$v] = $ar;
    }
}

print_r($newarray);


Output:

Array
(
    [NewYork] => Array
        (
            [city] => NewYork
            [cash] => 3000
        )

    [Philadelphia] => Array
        (
            [city] => Philadelphia
            [cash] => 2300
        )

)


Demo:
http://3v4l.org/D8PME

Saturday, August 6, 2022
4

You need to iterate over your results, adding a new entry to the output when you encounter a new team, or updating the points value when you find the same team again. This is most easily done by initially indexing the output by the team name, and then using array_values to re-index the array numerically:

$teams = array();
foreach ($results as $result) {
    $team = $result['team'];
    if (!isset($teams[$team])) {
        $teams[$team] = array('team' => $team, 'points' => $result['punti']);
    }
    else {
        $teams[$team]['points'] += $result['punti'];
    }
}
$teams = array_values($teams);
print_r($teams);

Output (for your sample data):

Array
(
    [0] => Array
        (
            [team] => Red Bull Racing
            [points] => 418
        )
    [1] => Array
        (
            [team] => Scuderia Ferrari
            [points] => 353
        )
    [2] => Array
        (
            [team] => Mercedes-AMG
            [points] => 516
        )
    [3] => Array
        (
            [team] => Racing Point F1
            [points] => 147
        )
    [4] => Array
        (
            [team] => Haas F1
            [points] => 127
        )
)

Demo on 3v4l.org

Friday, August 12, 2022
 
4

I'm assuming the following:

  1. every name entry in the original array has an identical desc_topic sub-array (e.g. they all have the same Apple/Banana/Orange values for every instance.
  2. the qtd_posts sub-array has the to-be-grouped values in the same corresponding slots (e.g. all '1' entries are to be summed together, all '2' entries summed together, etc...)
  3. You want to preserve the parent array keys so that all 'Edward Foo' entries will use the first key used by an Edward Foo entry (e.g. 0)

If that applies, then something like this should work:

$newarr = array();
$reverse_map = array();

foreach($array as $idx => $entry) {
    if (isset($reverse_map[$entry['name']]) {
         // have we seen this name before? retrieve its original index value
         $idx = $reverse_map[$entry['name']]; 
    } else {
         // nope, new name, so store its index value
         $reverse_map[$entry['name']] = $idx;
    }

    // copy the 'constant' values
    $newarr[$idx]['name'] = $entry['name'];
    $newarr[$idx]['desc_top'] = $entry['desc_topic'];

    // sum the qtd_post values to whatever we previously stored.        
    foreach($entry['qtd_posts'] as $x => $y) {
        $newarr[$idx]['qtd_posts'][$x] += $y;
    }
}
Tuesday, December 27, 2022
 
4

If you absolutely have to do this in PHP, then something like:

$data = array(
    array(
        'shelf' => 'Left',
        'weight' => '10.000',
        'piece' => 1,
    ),
    array(
        'shelf' => 'Right',
        'weight' => '04.000',
        'piece' => 12,
    ),
    array(
        'shelf' => 'Right',
        'weight' => '04.000',
        'piece' => 4,
    ),
    array(
        'shelf' => 'Right',
        'weight' => '07.000',
        'piece' => 8,
    ),
);


$newData = array();
$result = array_reduce(
    $data,
    function($newData, $value) {
        $key = $value['shelf'].$value['weight'];
        if (!isset($newData[$key])) {
            $newData[$key] = $value;
        } else {
            $newData[$key]['piece'] += $value['piece'];
        }
        return $newData;
    },
    $newData
);
var_dump($result);

will work, but I really do believe that you're creating major performance problems for yourself with your whole approach to this problem

Friday, August 5, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share