PHP的array_diff()函數在處理大數組時的效率問題

來源:互聯網
上載者:User

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);
// 迴圈第一個數組
foreach($firstArray as $key => $value) {
// 如果第二個數組中存在第一個數組的值
if (isset($secondArray[$value])) {
// 移除第一個數組中對應的元素
unset($firstArray[$key]);
}
}
return $firstArray;
}
?>

此方法只交換了第二個數組的 key 和 value,所以效率更高。
注意:PHP 內建的 array_diff() 函數可以處理多個數組,而本文提供的方法只處理了兩個數組的比較。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.