phparraysmultidimensional-arraysumgrouping

Sum the correlated values of two array columns


Array
(
    [start] => Array
        (
            [0] => mymail@google.mail
            [1] => antohermail@yahoo.com
            [2] => antohermail@yahoo.com
            [3] => mymail@google.mail
            [4] => 222222@google.mail
            [5] => mymail@google.mail
            [6] => bot001e08@lopbot001
            [7] => antohermail@yahoo.com
            [8] => mymail@google.mail
            [9] => bot001e02@lopbot001.mail
        )

    [name] => Array
        (
            [0] => 43
            [1] => 17
            [2] => 15
            [3] => 34
            [4] => 12
            [5] => 37
            [6] => 14
            [7] => 12
            [8] => 33
            [9] => 25
        )

)

This multi array has the same number of keys. I would like to show all different emails (start array) and count all values from name array.

So the desired output would be something like that:

mymail@google.mail: 43+34+37+23 = 137

antohermail@yahoo.com: 17 +15+ 12 = 44

222222@google.mail: 12

bot001e08@lopbot001: 14

bot001e02@lopbot001.mail: 25

With special function i could get result like this:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [mymail@google.mail] => 43
                    [antohermail@yahoo.com] => 17
                    [antohermail@yahoo.com] => 15
                )

            [1] => Array
                (
                    [mymail@google.mail] => 34
                    [222222@google.mail] => 12
                )

            [2] => Array
                (
                    [mymail@google.mail] => 37
                    [bot001e08@lopbot001] => 14
                    [222222@google.mail] => 12
                )

            [3] => Array
                (
                    [mymail@google.mail] => 33
                    [bot001e02@lopbot001.mail] => 25
                )

        )

)

But i still can not count the values from this multi array


Solution

  • Use this simple loop with nested indexes

    $mails = array();
            foreach ($data['start'] as $key => $value) {
                $mails[$value]['sum'] = @$mails[$value]['sum'] + $data['name'][$key];
            }
        
     print_r($mails);
    

    Result:

    (
    [mymail@google.mail] => Array
        (
            [sum] => 147
        )
    
    [antohermail@yahoo.com] => Array
        (
            [sum] => 44
        )
    
    [222222@google.mail] => Array
        (
            [sum] => 12
        )
    
    [bot001e08@lopbot001] => Array
        (
            [sum] => 14
        )
    
    [bot001e02@lopbot001.mail] => Array
        (
            [sum] => 25
        )
    

    )