PHP array comparison and merging for efficiency php array
$ Arr1 = array (1, 3, 5, 9, 34, 128,129 );
$ Arr2 = array (1, 3, 6, 128 );
$ Arr3 = array (, 78 );
The expected result is:
$ Res = array (1,128, 34,129 );
The rule is to merge the three arrays and put them forward with the highest degree of repetition.
// $ Arr1 $ arr2 $ arr3 must be desc or asc
// If only $ arr1 and $ arr2 are sorted, or $ arr4 is added.
// Thanks ~
Reply to discussion (solution)
$arr1 = array(1, 3, 5, 9,34,128,129);$arr2 = array(1, 3, 6, 22,33, 128);$arr3 = array(128,78,56,33,5,1);$t = array_count_values(array_merge($arr1, $arr2, $arr3));arsort($t);print_r(array_keys($t));
Array
(
[0] => 1
[1] => 128.
[2] => 5
[3] => 33
[4] => 3
[5] => 78
[6] => 56
[7] => 22
[8] = & gt; 129
[9] => 9
[10] => 34
[11] => 6
)
Although it is fast to use the interior function only, it does not fully meet your requirements.
Therefore, you need to write your own code.
$t = array_count_values(array_merge($arr1, $arr2, $arr3));$res = array();for($max=max($t); $max>0; $max--) $res = array_merge($res, array_keys($t, $max));print_r($res);
Array
(
[0] => 1
[1] => 128.
[2] => 3
[3] => 5
[4] => 33
[5] => 9
[6] => 34
[7] = & gt; 129
[8] => 6
[9] => 22
[10] => 78
[11] => 56
)
Well, I understand, the moderator is still awesome ~ I made a hard decision last night,
Array_diff is not powerful, so it is so redundant.
$ Arr1 = array (100, 15,200,); $ arr2 = array (,); $ arr3 = array ); $ res = array (); $ resHigh = array (); // Highly similar $ resMiddle = array (); // $ resLow = array (); // Low $ res = array_merge ($ arr1, $ arr2, $ arr3); $ res = my_array_unique ($ res); // exclude duplicates $ reshweigh = array_intersect ($ arr1, $ arr2, $ arr3); // intersection $ resLow = array_merge (array_diff ($ arr1, $ arr2, $ arr3), array_diff ($ arr2, $ arr1, $ arr3 ), array_diff ($ arr3, $ arr 1, $ arr2); // combined difference set $ res = array_diff ($ res, $ resHigh); // exclude High $ resMiddle = array_diff ($ res, $ resLow ); // exclude Low $ res = array_merge ($ reshweigh, $ resMiddle, $ resLow); function my_array_unique ($ array) {// exclude duplicates $ out = array (); foreach ($ array as $ key => $ value) {if (! In_array ($ value, $ out) {$ out [$ key] = $ value ;}} return $ out;} echo"";print_r($res);exit;/*( [0] => 1 [1] => 8 [2] => 9 [3] => 15 [4] => 2 [5] => 3 [6] => 4 [7] => 5 [8] => 6 [9] => 7 [10] => 10 [11] => 100 [12] => 200)*/