John Davidson

arrays - PHP - sum one or more values with the same key

0 comments
Message:


What is the best way to sum the 'val','val1','val2' field with the same 'color' for each different color:


I have the below array format. Add the key values in that array if the color have same values. Please help me out. Thanks in advance


Array
(
[0] => Array
(
[color]=> "red"
[val]=> 4
[val1]=> 4
[val2]=> 4
)
[1] => Array
(
[color]=> "green"
[val]=> 3
[val1]=> 3
[val2]=> 3
)
[2] => Array
(
[color]=> "blue"
[val]=> 1
[val1]=> 3
[val2]=> 3
)
[3] => Array
(
[color]=> "green"
[val]=> 6
[val1]=> 3
[val2]=> 3
)
[4] => Array
(
[color]=> "blue"
[val]=> 2
[val1]=> 3
[val2]=> 3
)
)

My Desired result :


 (
[color] => red
[val] => 4
[val1] => 4
[val2] => 4

)
(
[color] => green
[val] => 9
[val1] => 6
[val2] => 6

)
(
[color] => blue
[val] => 3
[val1] => 6
[val2] => 6

)


My Answer:
> Array
(
[0] => Array
(
[color] => red
[val] => 10
[val1] => 20
[val2] => 30
)

[1] => Array
(
[color] => blue
[val] => 15
[val1] => 25
[val2] => 35
)

[2] => Array
(
[color] => red
[val] => 5
[val1] => 15
[val2] => 25
)

[3] => Array
(
[color] => blue
[val] => 20
[val1] => 30
[val2] => 40
)
)

php
$sums = array();
foreach ($array as $item) {
$color = $item['color'];
if (!isset($sums[$color])) {
$sums[$color] = array('val' => 0, 'val1' => 0, 'val2' => 0);
}
$sums[$color]['val'] += $item['val'];
$sums[$color]['val1'] += $item['val1'];
$sums[$color]['val2'] += $item['val2'];
}

print_r($sums);


This code will output:


Array
(
[red] => Array
(
[val] => 15
[val1] => 35
[val2] => 55
)

[blue] => Array
(
[val] => 35
[val1] => 55
[val2] => 75
)
)

Rate this post

3 of 5 based on 1850 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us