Addition of matching array key params in PHP -
i have following array, in array there same dates key 112. need addition of arrays dates same.
array ( [0] => array ( [112] => 2015-02-17 [97] => 20.00 [84] => 13.00 ) [1] => array ( [112] => 2015-02-17 [97] => -5 [84] => 0 ) [2] => array ( [112] => 2015-02-17 [97] => -5 [84] => 0 ) [3] => array ( [112] => 2015-03-17 [97] => 10 [84] => 0 ) [4] => array ( [112] => 2015-03-17 [97] => -5 [84] => 0 ) [5] => array ( [112] => 2015-03-17 [97] => -5 [84] => 0 ) [6] => array ( [112] => 2015-01-17 [97] => 2 [84] => 0 ) [7] => array ( [112] => 2015-01-17 [97] => 13 [84] => 0 ) [8] => array ( [112] => 2015-01-17 [97] => 2 [84] => 0 ) )
for example above array need following result:
array ( [0] => array ( [112] => 2015-02-17 [97] => 10.00 [84] => 13.00 ) [1] => array ( [112] => 2015-03-17 [97] => 0 [84] => 0 ) [2] => array ( [112] => 2015-01-17 [97] => 17 [84] => 0 ) )
in resultant array need addition of array 112 key value date same.
i have thousands of records this. please suggest simple , fastest way. need preserve keys of inner arrays.
you need use foreach
loop , iterate each element in array.
$array = array( array( 112 => '2015-02-17', 97 => 20, 84 => 13 ), array( 112 => '2015-02-17', 97 => -5, 84 => 13 ), array( 112 => '2015-02-17', 97 => -5, 84 => 13 ), array( 112 => '2015-02-18', 97 => 10, 84 => 13 ), array( 112 => '2015-02-18', 97 => 10, 84 => 13 ), ); $result = array(); foreach ($array $item) { if (isset($result[$item[112]])) { foreach ($item $key => $value) { if ($key != 112) { # don't need sum 'date column' if (isset($result[$item[112]][$key])) { $result[$item[112]][$key] += $value; } else { $result[$item[112]][$key] = $value; } } } } else { $result[$item[112]] = $item; } } print_r(array_values($result));
Comments
Post a Comment