Home  >  Article  >  Backend Development  >  PHP的array_diff()函数在处理大数组时的效率问题_php技巧

PHP的array_diff()函数在处理大数组时的效率问题_php技巧

WBOY
WBOYOriginal
2016-05-17 09:14:25842browse

cisa 提交到 PHP 官方 BUG 页面上的方法

复制代码 代码如下:

/**
* 解决 php 5.2.6 以上版本 array_diff() 函数在处理
* 大数组时的需要花费超长时间的问题
*
* 整理:http://www.CodeBit.cn
* 来源:http://bugs.php.net/47643
*/
function array_diff_fast($data1, $data2) {
$data1 = array_flip($data1);
$data2 = array_flip($data2);
foreach($data2 as $hash => $key) {
if (isset($data1[$hash])) unset($data1[$hash]);
}
return array_flip($data1);
}
?>

根据 ChinaUnix 论坛版主 hightman 思路重写的方法
复制代码 代码如下:

/**
* 解决 php 5.2.6 以上版本 array_diff() 函数在处理大数组时的效率问题
* 根据 ChinaUnix 论坛版主 hightman 思路写的方法
*
* 整理:http://www.CodeBit.cn
* 参考:http://bbs.chinaunix.net/viewthread.php?tid=938096&rpid=6817036&ordertype=0&page=1#pid6817036
*/
function array_diff_fast($firstArray, $secondArray) {
// 转换第二个数组的键值关系
$secondArray = array_flip($secondArray);
// 循环第一个数组
foreach($firstArray as $key => $value) {
// 如果第二个数组中存在第一个数组的值
if (isset($secondArray[$value])) {
// 移除第一个数组中对应的元素
unset($firstArray[$key]);
}
}
return $firstArray;
}
?>

此方法只交换了第二个数组的 key 和 value,所以效率更高。
注意:PHP 内置的 array_diff() 函数可以处理多个数组,而本文提供的方法只处理了两个数组的比较。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn