时间:2021-07-01 10:21:17 帮助过:21人阅读
本文介绍下,一个自定义的求数组差集的函数array_different,效率要好于array_diff函数。有需要的朋友参考下。
php求数组差集,代码如下: $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 ' '; 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.','; } ?> |