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

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

WBOY
Release: 2016-06-23 13:56:25
Original
892 people have browsed it

如题

举例:

传入 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);
Copy after login
Array(    [0] => Array        (            [a] => 2            [b] => 6        )    [1] => Array        (            [a] => 5            [b] => 7        )    [2] => Array        (            [a] => 7            [b] => 13        ))
Copy after login

感谢版大~~~

$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);
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template