Multidimensional array addition

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 19:03:11

问题


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.


回答1:


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 ;
}


来源:https://stackoverflow.com/questions/17014239/multidimensional-array-addition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!