Home  >  Article  >  Backend Development  >  [伸手党]求个function,传入一个规律的二维数组,每个子数组都是键名相同的数组,键值都是整数,返回结果是二维数组多了一个子数组,是每个子数组的求和结果

[伸手党]求个function,传入一个规律的二维数组,每个子数组都是键名相同的数组,键值都是整数,返回结果是二维数组多了一个子数组,是每个子数组的求和结果

WBOY
WBOYOriginal
2016-06-23 13:56:25857browse

如题

举例:

传入 array(0=>array(a=>2,b=>6),1=>array(a=>5,b=>7));

得到结果是 array(0=>array(a=>2,b=>6),1=>array(a=>5,b=>7),2=>array(a=>7,b=>11));

工期紧 能省一点时间是一点, 伸手求一次...


回复讨论(解决方案)

$ar = array(  array( 'a' => 2, 'b' => 6),  array( 'a' => 5, 'b' => 7),);$t = array();foreach($ar as $r) {  foreach($r as $k=>$v) @$t[$k] += $v;}$ar[] = $t;print_r($ar);
Array(    [0] => Array        (            [a] => 2            [b] => 6        )    [1] => Array        (            [a] => 5            [b] => 7        )    [2] => Array        (            [a] => 7            [b] => 13        ))

感谢版大~~~

$ar = array(  array( 'a' => 2, 'b' => 6),  array( 'a' => 5, 'b' => 7),);$t = call_user_func_array('array_map', array_merge(array(null),$ar));$t = array_map('array_sum', $t);$t = array_combine(array_keys($ar[0]), $t);$ar[] = $t;print_r($ar);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:网页模块的添加Next article:php Laravel 框架之分页