PHP按照多个键值给数组分组合并
简介:
$array 为⼀堆数组,各数组键值为固定
$keys为分组依据,在$array中按照$keys所指定的键值将数组分组,并且将除$keys指定键值对应的值以外的值合并 1function groupBy($array,$keys){
2$i = 0;
3while($i < sizeof($array)){
4$x = sizeof($array) - 1;
5while ($x > $i) {
php 数组字符串转数组6//取数组交集并返回交集,保留键名
7$temp = array_intersect_assoc($array[$i],$array[$x]);
8if(!empty($temp)){
9// 取键名交集,并做⽐较,如果相交等于分组依据的键名,则说明两个⼦数组可以合并
10if(array_intersect_assoc($keys,array_keys($temp)) == $keys){
11foreach ($array[$i] as$k => $v) {
12if(!in_array($k,$keys)){
13$array[$i][$k] += $array[$x][$k];
14 }
15 }
16//将合并部分移出数组
17array_splice($array,$x,1);
18 }
19 }
20$x--;
21 }
22$i++;
23 }
24return$array;
25 }
26
27//测试:
28$arr = array(
29array(
30 'province' => 'Guangdong',
31 'city' => 'Guangzhou',
32 'num1' => 25,
33 'num2' => 15,
34 'num3' => 43,
35 ),
36array(
37 'province' => 'Guangdong',
38 'city' => 'Guangzhou',
39 'num1' => 25,
40 'num2' => 15,
41 'num3' => 43,
42 ),
43array(
44 'province' => 'Guangdong',
45 'city' => 'Guangzhou',
46 'num1' => 33,
47 'num2' => 24,
48 'num3' => 32,
49 ),
50array(
51 'province' => 'Jiangsu',
52 'city' => 'Nanjing',
53 'num1' => 25,
54 'num2' => 115,
55 'num3' => 423,
56 ),
57array(
58 'province' => 'Jiangsu',
59 'city' => 'Nanjing',
60 'num1' => 0,
61 'num2' => 15,
62 'num3' => 1,
63 ),
64array(
65 'province' => 'Jiangsu',
66 'city' => 'Nanjing',
67 'num1' => 5,
68 'num2' => 2,
69 'num3' => 4,
70 ),
71array(
72 'province' => 'Jiangsu',
73 'city' => 'Nanjing',
74 'num1' => 5,
75 'num2' => 2,
76 'num3' => 4,
77 ),
78array(
79 'province' => 'Jiangsu',
80 'city' => 'Nanjing',
81 'num1' => 5,
82 'num2' => 2,
83 'num3' => 4,
84 ),
85array(
86 'province' => 'Guangdong',
87 'city' => 'Guangzhou',
88 'num1' => 1,
89 'num2' => 2,
90 'num3' => 3,
91 ),
92array(
93 'province' => 'Shanghai',
94 'city' => 'Shanghai',
95 'num1' => 25,
96 'num2' => 15,
97 'num3' => 43,
98 ),
99array(
100 'province' => 'Jiangsu', 101 'city' => 'Nanjing',
102 'num1' => 25,
103 'num2' => 15,
104 'num3' => 43,
105 ),
106array(
107 'province' => 'Henan', 108 'city' => 'Zhengzhou', 109 'num1' => 25,
110 'num2' => 15,
111 'num3' => 43,
112 ),
113array(
114 'province' => 'Hunan', 115 'city' => 'Changsha',
116 'num1' => 25,
117 'num2' => 15,
118 'num3' => 43,
119 ),
120array(
121 'province' => 'Hunan', 122 'city' => 'Changsha',
123 'num1' => 3,
124 'num2' => 4,
125 'num3' => 5,
126 ),
127 );
128$keys = array(
129 'province',
130 'city'
131 );
132$arr = groupBy($arr,$keys);
输出:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论