I have an array:
$result = array(
'a' => 15,
'b' => 25,
'a' => 10,
'c' => 6,
'k' => 10
);
I need the sum of same key values.
i.e. output like:
$result = array(
'a' => 25,
'b' => 25,
'c' => 6,
'k' => 10
);
This is impossible, in an associative array the keys are unique by definition. It wouldn't be quite associative otherwise.
You can't have multiple same keys in an array. If you want multiple keys in the same array you should create a multidimensional array:
$result = array();
$result[KEY1 (or empty)] = array(
'a' => 15,
'b' => 25,
'c' => 6,
'k' => 10
);
$result[KEY2 (or empty)] = array(
'a' => 15,
'b' => 25,
'c' => 6,
'k' => 10
);
If you want the sum of the same key's you can use something like this:
function getSum($key, $array)
{
$sum = 0;
foreach($result as $array)
{
if( array_key_exists($key, $array) && is_numeric($array[$key]) )
{
$sum += $array[$key];
}
}
return $sum;
}
So with this function you can call:
$sum = getSum('a', $result);
Why not use an object? If you add logic to adding values, you won't need some fancy foreach()
loops to calculate the sum (demo)
class UniqueList {
private $data = array();
public function insert($key, $value) {
if (isSet($this->data[$key]))
$this->data[$key] += $value;
else
$this->data[$key] = $value;
}
public function getAll() {
return $this->data;
}
}
$result = new UniqueList();
$result->insert('a', 5);
$result->insert('b', 15);
$result->insert('c', 25);
$result->insert('a', 23);