我需要一个值进行比较,以一组阵列。不过,我需要在比较的foreach多个值。如果使用in_array,它可以是缓慢的,真正的慢。有没有更快的替代方案?我现在的code是
I need to compare a value to a set of array. However, I need to compare multiple values in foreach. If using in_array, it can be slow, real slow. Is there any faster alternative? My current code is
foreach($a as $b){
in_array($b, $array);
}
感谢你。
您可以使用的 和array_diff
来计算对 $阵列。这会给你所有的值不在 $阵列
或 $ A
。
You could use array_diff
to compute the difference between the $a
array against $array
. This would give you all the values not in $array
or $a
.
从手动例如:
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
print_r( array_diff($array1, $array2) );
Array
(
[1] => blue
)
或者你也可以使用 和array_intersect
发现那些在那些阵列。
Or you can use array_intersect
to find those that are in those arrays.
和array_intersect
从PHP手册举例:
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
print_r( array_intersect($array1, $array2) );
Array
(
[a] => green
[0] => red
)
选择您需要的人。
Pick the one you need.