php 求数组差集的自定义函数(效率优于array_diff函数)

发布时间:2020-06-16编辑:脚本学堂
本文介绍下,一个自定义的求数组差集的函数array_different,效率要好于array_diff函数。有需要的朋友参考下。

php求数组差集,代码如下:

<?php
/**
* func: array_different
* 功能:求数组的差集
* edit:www.jb200.com
*/
function array_different($array_1, $array_2) {
$array_2 = array_flip($array_2); //将数组键值调换

foreach ($array_1 as $key => $val) {
if (isset($array_2[$val])) {
unset($array_1[$key]);
}
}

return $array_1;
}

function runtime($mode = 0) {
static $t;

if (!$mode) {
$t = microtime();
return;
}

$t1 = microtime();
list($m0, $s0) = explode(" ", $t);
list($m1, $s1) = explode(" ", $t1);

return sprintf("%.3f", ($s1 + $m1 - $s0 - $m0) * 1000);
}

$array_1 = array();
$array_2 = array();

for ($i = 0; $i <= 5000; $i++) {
$array_1[$i] = mt_rand(0, 100);
$array_2[$i] = mt_rand(0, 100);
}

runtime(); //计时开始
$arr_diff = array_diff($array_1, $array_2);
echo runtime(1); //计时结束并输出计时结果
echo '<br>';

foreach ($arr_diff as $key => $val) {
echo $val.',';
}

runtime(); //计时开始
$arr_diff2 = array_different($array_1, $array_2);
echo runtime(2); //计时结束并且输出计时结果

foreach ($arr_diff2 as $key => $val) {
echo $val.',';
}
?>