php二维数组,相同值求和,并返回新的数组
已知数组:Array([25]=>Array([0]=>1[1]=>107[2]=>100[3]=>83[4]=>44[5]=>111)[26]=>Array([0]=>...
已知数组:
Array (
[25] => Array ( [0] => 1 [1] => 107 [2] => 100 [3] => 83 [4] => 44 [5] => 111 )
[26] => Array ( [0] => 100 [1] => 109 [2] => 126 [3] => 86 [4] => 93 [5] => 22)
[27] => Array ( [0] => 10 [1] => 113 [2] => 70 [3] => 57 [4] => 61 [5] => 44)
[28] => Array ( [0] => 110 [1] => 66 [2] => 36 [3] => 41 [4] => 25 [5] => 45 ) ) 展开
Array (
[25] => Array ( [0] => 1 [1] => 107 [2] => 100 [3] => 83 [4] => 44 [5] => 111 )
[26] => Array ( [0] => 100 [1] => 109 [2] => 126 [3] => 86 [4] => 93 [5] => 22)
[27] => Array ( [0] => 10 [1] => 113 [2] => 70 [3] => 57 [4] => 61 [5] => 44)
[28] => Array ( [0] => 110 [1] => 66 [2] => 36 [3] => 41 [4] => 25 [5] => 45 ) ) 展开
2个回答
展开全部
<?php
$arr=array(
25 => Array ( 0 => 1, 1 => 107, 2 => 100, 3 => 83, 4 => 44 ,5 => 111 ),
26 => Array ( 0 => 100, 1 => 109 ,2 => 126, 3 => 86, 4 => 93, 5 => 22),
27 => Array ( 0 => 10 ,1 => 113, 2 => 70, 3 => 57, 4 => 61, 5 => 44) ,
28 => Array ( 0 => 110, 1 => 66, 2 => 36, 3 => 41, 4 => 25, 5 => 45 )
);
$res_arr=array(); //结果数据 key 为 1 107 等值 ,value 为加和
$key_arr=array(); // value为 $res_arr 所有key
foreach($arr as $value){
foreach($value as $v){
if(in_array($v, $key_arr)){
$res_arr[$v]=$v+$res_arr[$v];
}else{
$res_arr[$v]=$v;
$key_arr[]=$v;
}
}
}
var_dump($res_arr);
/*
结果:
array
1 => int 1
107 => int 107
100 => int 200 //出现2次
83 => int 83
44 => int 88 //出现2次
111 => int 111
109 => int 109
126 => int 126
86 => int 86
93 => int 93
22 => int 22
10 => int 10
113 => int 113
70 => int 70
57 => int 57
61 => int 61
110 => int 110
66 => int 66
36 => int 36
41 => int 41
25 => int 25
45 => int 45
*/
;
$arr=array(
25 => Array ( 0 => 1, 1 => 107, 2 => 100, 3 => 83, 4 => 44 ,5 => 111 ),
26 => Array ( 0 => 100, 1 => 109 ,2 => 126, 3 => 86, 4 => 93, 5 => 22),
27 => Array ( 0 => 10 ,1 => 113, 2 => 70, 3 => 57, 4 => 61, 5 => 44) ,
28 => Array ( 0 => 110, 1 => 66, 2 => 36, 3 => 41, 4 => 25, 5 => 45 )
);
$res_arr=array(); //结果数据 key 为 1 107 等值 ,value 为加和
$key_arr=array(); // value为 $res_arr 所有key
foreach($arr as $value){
foreach($value as $v){
if(in_array($v, $key_arr)){
$res_arr[$v]=$v+$res_arr[$v];
}else{
$res_arr[$v]=$v;
$key_arr[]=$v;
}
}
}
var_dump($res_arr);
/*
结果:
array
1 => int 1
107 => int 107
100 => int 200 //出现2次
83 => int 83
44 => int 88 //出现2次
111 => int 111
109 => int 109
126 => int 126
86 => int 86
93 => int 93
22 => int 22
10 => int 10
113 => int 113
70 => int 70
57 => int 57
61 => int 61
110 => int 110
66 => int 66
36 => int 36
41 => int 41
25 => int 25
45 => int 45
*/
;
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询