PHP 数组比较合并,求效率

WBOY
Lepaskan: 2016-06-23 14:13:36
asal
1133 orang telah melayarinya

php 数组

$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);

想得到的结果是:
$res = array(1,128,3,5,33,9,34,129,6,22,78,56);

规则是:将3数组合并,重复度最高的往前放
//$arr1 $arr2 $arr3一定是desc就是asc排列

//如果只有$arr1和$arr2两个排序呢,或是再添个$arr4呢
//Thanks~

回复讨论(解决方案)

$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));
Salin selepas log masuk
Array
(
[0] => 1
[1] => 128
[2] => 5
[3] => 33
[4] => 3
[5] => 78
[6] => 56
[7] => 22
[8] => 129
[9] => 9
[10] => 34
[11] => 6
)
仅用内饰函数虽然快,但并不完全符合你的要求
所以还需要自己写点代码
$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);
Salin selepas log masuk
Array
(
[0] => 1
[1] => 128
[2] => 3
[3] => 5
[4] => 33
[5] => 9
[6] => 34
[7] => 129
[8] => 6
[9] => 22
[10] => 78
[11] => 56
)


嗯,明白,还是版主给力啊~我昨晚也生搬硬套一个,
array_diff不给力啊,所以如此冗余

$arr1 = array(1,2,3,4,5,6,7,8,9,10);$arr2 = array(1,8,9,15,100);$arr3 = array(1,8,15,200);$res  = array();$resHigh	    = array();//高度相似$resMiddle	  = array();//中$resLow		 = array();//低$res	 = array_merge($arr1,$arr2,$arr3);$res	 = my_array_unique($res);				//排除重复$resHigh = array_intersect($arr1,$arr2,$arr3);	//交集$resLow  = array_merge(array_diff($arr1,$arr2,$arr3),array_diff($arr2,$arr1,$arr3),array_diff($arr3,$arr1,$arr2));//组合差集$res	 = array_diff($res,$resHigh);			//排除High$resMiddle = array_diff($res,$resLow);			//排除Low$res	 = array_merge($resHigh,$resMiddle,$resLow);function my_array_unique($array){//排除重复   $out = array();   foreach ($array as $key=>$value) {       if (!in_array($value, $out)){           $out[$key] = $value;        }   }   return $out;} echo "<pre class="brush:php;toolbar:false">";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)*/
Salin selepas log masuk

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan