PHP的array_diff()函数在处理大数组时的效率问题
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() 函数可以处理多个数组,而本文提供的方法只处理了两个数组的比较。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment
