3

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.

4

1 回答 1

1

您可以使用

$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);

观看现场演示

上面的例子仅限于2个数组..如果你有更多喜欢10..你可以使用这个函数稍作修改

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

或者

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

观看现场演示

功能

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 ;
}
于 2013-06-09T21:31:22.607 回答