我有两个数组,数组A包含一个长列表,其中包含一些我想删除的元素.数组B是我希望从数组A中删除的那些元素的完整列表.
实现这一目标的最有效方法是什么?
use*_*291 12
array_diff是明显的答案,但既然你已经要求最有效的方法,那么这是一个测试
$big = range(1, 90000);
$remove = range(500, 600);
$ts = microtime(true);
$result = array_diff($big, $remove);
printf("%.2f\n", microtime(true) - $ts);
$ts = microtime(true);
$map = array_flip($remove);
$result = array();
foreach($big as $e)
if(!isset($map[$e]))
$result[] = $e;
printf("%.2f\n", microtime(true) - $ts);
Run Code Online (Sandbox Code Playgroud)
在我的机器上打印
0.67
0.03
Run Code Online (Sandbox Code Playgroud)
因此,基于散列的查找的简单循环比array_diff快大约20倍.
在手册中给出了array_dif()这个例子:
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Array
(
[1] => blue
)
Run Code Online (Sandbox Code Playgroud)
返回一个数组,其中包含array1中任何其他任何数组中都不存在的条目.