Brief introduction:
$array is a bunch of arrays, each array key value is fixed
$keys is grouped by, grouping the array in $array according to the key value specified by $keys, and merging values other than those corresponding to the $keys specified key value
1 functionGroupBy ($array,$keys){2 $i= 0;3 while($i<sizeof($array)){4 $x=sizeof($array)-1;5 while($x>$i) {6 //takes an array intersection and returns the intersection, preserving the key name7 $temp=Array_intersect_assoc($array[$i],$array[$x]);8 if(!Empty($temp)){9 //The intersection of the key names, and the comparison, if the intersection is equal to the group by the key name, then two sub-arrays can be mergedTen if(Array_intersect_assoc($keys,Array_keys($temp)) ==$keys){ One foreach($array[$i] as $k=$v) { A if(!In_array($k,$keys)){ - $array[$i][$k] +=$array[$x][$k]; - } the } - //move Merge parts to groups - Array_splice($array,$x, 1); - } + } - $x--; + } A $i++; at } - return $array; - } - - //Test: - $arr=Array( in Array( -' Province ' = ' Guangdong ', to' City ' = ' Guangzhou ', +' NUM1 ' = 25, -' num2 ' = 15, the' num3 ' = 43, *), $ Array(Panax Notoginseng' Province ' = ' Guangdong ', -' City ' = ' Guangzhou ', the' NUM1 ' = 25, +' num2 ' = 15, A' num3 ' = 43, the), + Array( -' Province ' = ' Guangdong ', $' City ' = ' Guangzhou ', $' Num1 ' = 33, -' num2 ' = 24, -' num3 ' = 32, the), - Array(Wuyi' Province ' = ' Jiangsu ', the' City ' = ' Nanjing ', -' NUM1 ' = 25, Wu' num2 ' = 115, -' num3 ' = 423, About), $ Array( -' Province ' = ' Jiangsu ', -' City ' = ' Nanjing ', -' Num1 ' = 0, A' num2 ' = 15, +' Num3 ' = 1, the), - Array( $' Province ' = ' Jiangsu ', the' City ' = ' Nanjing ', the' Num1 ' = 5, the' Num2 ' = 2, the' Num3 ' = 4, -), in Array( the' Province ' = ' Jiangsu ', the' City ' = ' Nanjing ', About' Num1 ' = 5, the' Num2 ' = 2, the' Num3 ' = 4, the), + Array( -' Province ' = ' Jiangsu ', the' City ' = ' Nanjing ',Bayi' Num1 ' = 5, the' Num2 ' = 2, the' Num3 ' = 4, -), - Array( the' Province ' = ' Guangdong ', the' City ' = ' Guangzhou ', the' Num1 ' = 1, the' Num2 ' = 2, -' Num3 ' = 3, the), the Array( the' Province ' = ' Shanghai ',94' City ' = ' Shanghai ', the' NUM1 ' = 25, the' num2 ' = 15, the' num3 ' = 43,98), About Array( -' Province ' = ' Jiangsu ',101' City ' = ' Nanjing ',102' NUM1 ' = 25,103' num2 ' = 15,104' num3 ' = 43, the),106 Array(107' Province ' = ' Henan ',108' City ' = ' Zhengzhou ',109' NUM1 ' = 25, the' num2 ' = 15,111' num3 ' = 43, the),113 Array( the' Province ' = ' Hunan ', the' City ' = ' Changsha ', the' NUM1 ' = 25,117' num2 ' = 15,118' num3 ' = 43,119), - Array(121' Province ' = ' Hunan ',122' City ' = ' Changsha ',123' Num1 ' = 3,124' Num2 ' = 4, the' Num3 ' = 5,126),127 ); - $keys=Array(129' Province ', the' City '131 ); the $arr= GroupBy ($arr,$keys);
Output:
PHP Grouping of arrays by multiple key values