问题描述
array_diff()
如何工作?它显然不能如下工作:
How does array_diff()
work? It obviously couldn't work as follows:
function array_diff($arraya, $arrayb)
{
$diffs = array();
foreach ($arraya as $keya => $valuea)
{
$equaltag = 0;
foreach ($arrayb as $valueb)
{
if ($valuea == $valueb)
{
$equaltag =1;
break;
}
}
if ($equaltag == o)
{
$diffs[$keya]=$valuea;
}
}
return $diffs;
} //couldn't be worse than this
有人知道更好的解决方案吗?
Does anyone know a better solution?
编辑@animuson:
EDIT @animuson:
function array_diff($arraya, $arrayb)
{
foreach ($arraya as $keya => $valuea)
{
if (in_array($valuea, $arrayb))
{
unset($arraya[$keya]);
}
}
return $arraya;
}
推荐答案
UPDATE
参见下文以获取更快/更好的代码.
see below for faster/better code.
array_diff 在 php 5.3.4 中的表现要好得多,但仍然比 Leo 的函数慢约 10 倍.
array_diff behaviour is much better in php 5.3.4, but still ~10 times slower than Leo's function.
另外值得注意的是,这些函数并不严格等同于 array_diff
,因为它们不维护数组键,即 my_array_diff(x,y) == array_values(array_diff(x,y))
.
also it's worth noting that these functions are not strictly equivalent to array_diff
since they don't maintain array keys, i.e. my_array_diff(x,y) == array_values(array_diff(x,y))
.
/更新
更好的解决方案是使用哈希映射
function my_array_diff($a, $b) {
$map = $out = array();
foreach($a as $val) $map[$val] = 1;
foreach($b as $val) if(isset($map[$val])) $map[$val] = 0;
foreach($map as $val => $ok) if($ok) $out[] = $val;
return $out;
}
$a = array('A', 'B', 'C', 'D');
$b = array('X', 'C', 'A', 'Y');
print_r(my_array_diff($a, $b)); // B, D
基准
function your_array_diff($arraya, $arrayb)
{
foreach ($arraya as $keya => $valuea)
{
if (in_array($valuea, $arrayb))
{
unset($arraya[$keya]);
}
}
return $arraya;
}
$a = range(1, 10000);
$b = range(5000, 15000);
shuffle($a);
shuffle($b);
$ts = microtime(true);
my_array_diff($a, $b);
printf("ME =%.4f\n", microtime(true) - $ts);
$ts = microtime(true);
your_array_diff($a, $b);
printf("YOU=%.4f\n", microtime(true) - $ts);
结果
ME =0.0137
YOU=3.6282
有什么问题吗?;)
而且,只是为了好玩,
$ts = microtime(true);
array_diff($a, $b);
printf("PHP=%.4f\n", microtime(true) - $ts);
结果
ME =0.0140
YOU=3.6706
PHP=19.5980
太不可思议了!
这篇关于array_diff 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!