简介:
$array 为一堆数组,各数组键值为固定
$keys为分组依据,在$array中按照$keys所指定的键值将数组分组,并且将除$keys指定键值对应的值以外的值合并
1 function groupBy($array,$keys){ 2 $i = 0; 3 while($i < sizeof($array)){ 4 $x = sizeof($array) - 1; 5 while ($x > $i) { 6 //取数组交集并返回交集,保留键名 7 $temp = array_intersect_assoc($array[$i],$array[$x]); 8 if(!empty($temp)){ 9 // 取键名交集,并做比较,如果相交等于分组依据的键名,则说明两个子数组可以合并 10 if(array_intersect_assoc($keys,array_keys($temp)) == $keys){ 11 foreach ($array[$i] as $k => $v) { 12 if(!in_array($k,$keys)){ 13 $array[$i][$k] += $array[$x][$k]; 14 } 15 } 16 //将合并部分移出数组 17 array_splice($array,$x,1); 18 } 19 } 20 $x--; 21 } 22 $i++; 23 } 24 return $array; 25 } 26 27 //测试: 28 $arr = array( 29 array( 30 'province' => 'Guangdong', 31 'city' => 'Guangzhou', 32 'num1' => 25, 33 'num2' => 15, 34 'num3' => 43, 35 ), 36 array( 37 'province' => 'Guangdong', 38 'city' => 'Guangzhou', 39 'num1' => 25, 40 'num2' => 15, 41 'num3' => 43, 42 ), 43 array( 44 'province' => 'Guangdong', 45 'city' => 'Guangzhou', 46 'num1' => 33, 47 'num2' => 24, 48 'num3' => 32, 49 ), 50 array( 51 'province' => 'Jiangsu', 52 'city' => 'Nanjing', 53 'num1' => 25, 54 'num2' => 115, 55 'num3' => 423, 56 ), 57 array( 58 'province' => 'Jiangsu', 59 'city' => 'Nanjing', 60 'num1' => 0, 61 'num2' => 15, 62 'num3' => 1, 63 ), 64 array( 65 'province' => 'Jiangsu', 66 'city' => 'Nanjing', 67 'num1' => 5, 68 'num2' => 2, 69 'num3' => 4, 70 ), 71 array( 72 'province' => 'Jiangsu', 73 'city' => 'Nanjing', 74 'num1' => 5, 75 'num2' => 2, 76 'num3' => 4, 77 ), 78 array( 79 'province' => 'Jiangsu', 80 'city' => 'Nanjing', 81 'num1' => 5, 82 'num2' => 2, 83 'num3' => 4, 84 ), 85 array( 86 'province' => 'Guangdong', 87 'city' => 'Guangzhou', 88 'num1' => 1, 89 'num2' => 2, 90 'num3' => 3, 91 ), 92 array( 93 'province' => 'Shanghai', 94 'city' => 'Shanghai', 95 'num1' => 25, 96 'num2' => 15, 97 'num3' => 43, 98 ), 99 array( 100 'province' => 'Jiangsu', 101 'city' => 'Nanjing', 102 'num1' => 25, 103 'num2' => 15, 104 'num3' => 43, 105 ), 106 array( 107 'province' => 'Henan', 108 'city' => 'Zhengzhou', 109 'num1' => 25, 110 'num2' => 15, 111 'num3' => 43, 112 ), 113 array( 114 'province' => 'Hunan', 115 'city' => 'Changsha', 116 'num1' => 25, 117 'num2' => 15, 118 'num3' => 43, 119 ), 120 array( 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);
输出: