-5

Following is my array. I need to add its Sum field according to each emp_firstname. Some has only one time coming, some coming two times. how can we sum the field and make the array unique?

Array
(
    [0] => Array
        (
            [emp_firstname] => Alistair
            [non_pm] => AMZ
            [sum] => 2
        )


    [1] => Array
        (
            [emp_firstname] => Shakkeer
            [non_pm] => SHK
            [sum] => 3
        )

    [2] => Array
        (
            [emp_firstname] => Waqas
            [non_pm] => WAS
            [sum] => 12
        )

    [3] => Array
        (
            [emp_firstname] => Zain
            [non_pm] => ZAI
            [sum] => 9
        )


    [4] => Array
        (
            [emp_firstname] => Shakkeer
            [gud_pmeditor] => SHK
            [sum] => 4
        )

    [5] => Array
        (
            [emp_firstname] => Zain
            [gud_pmeditor] => ZAI
            [sum] => 2
        )

)
Rahul
  • 18,271
  • 7
  • 41
  • 60
Pradeep.T.P
  • 133
  • 1
  • 1
  • 6
  • Have you tried anything yet? A simple `foreach` into another array should do it. – Nigel Ren May 20 '19 at 10:57
  • @AnuragSrivastava is right. It's literally 3 lines of code. Give it a try and if you don't make it i will post the answer for you. – pr1nc3 May 20 '19 at 11:03

1 Answers1

1

You can get the desired result using this approach

$res=[];
foreach($arr as $val){
  if(array_key_exists($val['emp_firstname'], $res))
    $res[$val['emp_firstname']]['sum'] = ($res[$val['emp_firstname']]['sum'] + $val['sum']);
  else
    $res[$val['emp_firstname']] = $val;
}

Live Demo

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20