<?php $arr = [ [ 'user_id' => 120, 'username' => 'test1', 'count' => 2 ], [ 'user_id' => 120, 'username' => 'test1', 'count' => 3 ], [ 'user_id' => 110, 'username' => 'test2', 'count' => 2 ] ]; /** loop through "$arr" and sum the "count" values based on the "user_id" */ $result = array_reduce($arr, function ($a, $c) { /** index the resulting array by the "user_id" value which allows for instant lookup in case of duplicate "user_id" value */ $a[$c['user_id']] = [ 'user_id' => $c['user_id'], 'username' => $c['username'], /** sum the "count" values * the first iteration will have an empty array * so we should check for existance before getting the value in order to prevent bugs */ 'count' => ($a[$c['user_id']]['count'] ?? 0) + $c['count'] ]; return $a; }, []); var_export($result);
You have javascript disabled. You will not be able to edit any code.