php - Sum of two indexes which are having same values with multi dimension Array -
i working multi dimensional array below php,
$return_array= array ( [0] => array ( [0] => 3_mar_2017 [1] => 0 [2] => 19 [3] => 7 [4] => 13 [5] => 3 [6] => 0 [7] => 42 ) [1] => array ( [0] => yet closed [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 1 [6] => 0 [7] => 1 ) [2] => array ( [0] => 3_mar_2017 [1] => 0 [2] => 7 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 7 ) [3] => array ( [0] => 4_apr_2017 [1] => 0 [2] => 8 [3] => 4 [4] => 0 [5] => 0 [6] => 0 [7] => 12 ) )
on 0th , 2nd indexs -> sub array of indexes -> 0th index common "3_mar_2017" ,i want sum 2 indexes , want result shown below,
$final_return = array ( [0] => array ( [0] => 3_mar_2017 [1] => 0 [2] => 26 [3] => 7 [4] => 13 [5] => 3 [6] => 0 [7] => 49 ) [1] => array ( [0] => yet closed [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 1 [6] => 0 [7] => 1 ) [2] => array ( [0] => 4_apr_2017 [1] => 0 [2] => 8 [3] => 4 [4] => 0 [5] => 0 [6] => 0 [7] => 12 ) )
my tried code loop below,
$tem_array = array(); $final_return = array(); foreach ($return_array $unique) { if (!in_array($unique[0], $tem_array)) { array_push($tem_array, $unique[0]); $final_return[] = $unique; } else { $index = array_search($unique[0], $tem_array); ($i = 1; $i < count($unique); $i++) { $final_return[$index][$i] = $final_return[$index][$i] + $unique[$i]; } } }
but if array size large ,may take time there simple solution. can person me required result minimum code ? appreciate best answer.
hope looking for
$temp1 = array(); $result = array(); foreach ($myarray $temp) { if (!in_array($temp[0], $temp1)) { array_push($temp1, $temp[0]); $result[] = $temp; } else { $id = array_search($temp[0], $temp1); ($i = 1; $i <= count($temp); $i++) { $result[$id][$i] = $result[$id][$i] + $temp[$i]; } } }
your first array like
array ( [0] => array ( [0] => 13 [1] => 1 [2] => 2 [3] => 3 ) [1] => array ( [0] => 14 [1] => 5 [2] => 6 [3] => 7 ) [2] => array ( [0] => 13 [1] => 1 [2] => 2 [3] => 3 ) )
and result
array ( [0] => array ( [0] => 13 [1] => 2 [2] => 4 [3] => 6 ) [1] => array ( [0] => 14 [1] => 5 [2] => 6 [3] => 7 ) )
Comments
Post a Comment