Question

Suppose that I have two arrays:

$v_4 = array(array(1,2,3),array(4,5,6));
$v_5 = array(array(7,8,9),array(10,11,12));

How should I construct an addition function to add across these arrays so as to get:

$new_array = array(array(8,10,12),array(14,16,18));

I know I need to utilise array_map somehow, but I am unsure how to proceed in the multidimensional case.

Was it helpful?

Solution

You can use

$new = array();
foreach(array_map(null, $v_4, $v_5) as $var) {
    $data = call_user_func_array("array_map", array_merge(array(null) , $var));
    $new[] = array_map("array_sum", $data);
}
print_r($new);

See Live DEMO

The Example above is only limited to 2 arrays .. if you have more like 10 .. you can use this function with a little modification

print_r(array_sum_colums($v_4,$v_5,$v_6));

Or

print_r(array_sum_colums(array($v_4,$v_5,$v_6)));

See Live DEMO

Function

function array_sum_colums() {
    $args = count(func_get_args()) == 1 ? func_get_arg(0) : func_get_args();
    $arg = call_user_func_array("array_map", array_merge(array(null),$args));
    $new = array();
    foreach($arg as $var) {
        $data = call_user_func_array("array_map", array_merge(array(null), $var));
        $new[] = array_map("array_sum", $data);
    }
    return $new ;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top