PHP的array_diff()函數在處理大數組時的效率問題
更新時間:2011年11月27日 23:15:31 作者:
PHP 5.2.6 以上版本的 array_diff() 函數在處理大數組時,需要花費超長時間,這個 bug 已經被官方確認;在這個問題被修復之前或者在我們不能控制 PHP 版本的時候,可以使用本文提供的方法
cisa 提交到 PHP 官方 BUG 頁面上的方法
<?php
/**
* 解決 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
/**
* 解決 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);
// 循環(huán)第一個數組
foreach($firstArray as $key => $value) {
// 如果第二個數組中存在第一個數組的值
if (isset($secondArray[$value])) {
// 移除第一個數組中對應的元素
unset($firstArray[$key]);
}
}
return $firstArray;
}
?>
此方法只交換了第二個數組的 key 和 value,所以效率更高。
注意:PHP 內置的 array_diff() 函數可以處理多個數組,而本文提供的方法只處理了兩個數組的比較。
復制代碼 代碼如下:
<?php
/**
* 解決 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
/**
* 解決 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);
// 循環(huán)第一個數組
foreach($firstArray as $key => $value) {
// 如果第二個數組中存在第一個數組的值
if (isset($secondArray[$value])) {
// 移除第一個數組中對應的元素
unset($firstArray[$key]);
}
}
return $firstArray;
}
?>
此方法只交換了第二個數組的 key 和 value,所以效率更高。
注意:PHP 內置的 array_diff() 函數可以處理多個數組,而本文提供的方法只處理了兩個數組的比較。
相關文章
PHP使用new StdClass()創(chuàng)建空對象的方法分析
這篇文章主要介紹了PHP使用new StdClass()創(chuàng)建空對象的方法,結合具體實例形式分析了php空對象的創(chuàng)建與使用方法,需要的朋友可以參考下2017-06-06PHP curl get post 請求的封裝函數示例【get、post、put
這篇文章主要介紹了PHP curl get post 請求的封裝函,包含了php使用curl針對get、post、put、delete等請求類型進行封裝的操作技巧,以及CURLOPT_CUSTOMREQUEST控制DELETE、PUT請求類型的實現方法,需要的朋友可以參考下2023-04-04