Imgagining我有两个数组
arr[]={"red","blue","green"}
arr2[]={"red","violet","black"}
我将如何比较两个数组以获得两个数组共有的结果..
为此结果为红色......
我将如何在php中执行此操作(简单方法)...任何人都可以建议???
答案 0 :(得分:6)
使用array_intersect
功能。
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "violet", "black", "red");
$result = array_intersect($array1, $array2);
print_r($result);
<强>结果:强>
Array
(
[0] => red
)
答案 1 :(得分:3)
快速说明:
http://php.net/manual/en/function.array-intersect.php
该函数接受多个数组并返回一个数组,其中只包含每个数组中的ONLY元素。
在交叉结果之前,此片段将所有多维数组和UNIONS组合在一起:
($multi1[0] U $multi1[1] U ... U $multi1[n]) INTERSECT ($multi2[0] U $multi2[1] U ... U $multi2[m])
:
$result = null;
foreach(array($multi1, $multi2, $multi3) as $multi) {
$merge = array();
foreach($multi as $array) {
$merge = array_merge($merge, $array);
}
if($result == null) {
$result = $merge;
} else {
$result = array_intersect($merge, $result);
}
}
在交叉结果之前,此片段将所有多维数组和UNIONS组合在一起:
($multi1[0] INTERSECT $multi1[1] INTERSECT ... INTERSECT $multi1[n]) INTERSECT ($multi2[0] INTERSECT $multi2[1] INTERSECT ... INTERSECT $multi2[m])
:
$result_all = null;
foreach(array($multi1, $multi2, $multi3) as $multi) {
$result = null;
foreach($multi as $array) {
if($result == null) {
$result = $array;
} else {
$result = array_intersect($array, $result);
}
}
if($result_all == null) {
$result_all = $result;
} else {
$result_all = array_intersect($result, $result_all);
}
}
为了使阅读更简单,我对INTERSECT所有情况进行了递归:
function array_intersect_multi($arrays, $dim = 1) {
$result = null;
foreach($arrays as $array) {
$tmp = $dim > 1 ? array_intersect_multi($array, $dim - 1) : $array;
if($result == null) {
$result = $tmp;
} else {
$result = array_intersect($tmp, $result);
}
}
return $result;
}
像这样使用:
$array1 = array(array('1', '2', '3'), array('3', '5', '0'));
$array2 = array(array('5', '3', '7'), array('3', '7', '8'));
$result = array_intersect_multi(array($array1, $array2), 3);
注意维度3,因为我们传入的数组是:
array(
array(
array('1', '2', '3'),
array('3', '5', '0')
),
array(
array('5', '3', '7'),
array('3', '7', '8')
)
)
结果应为:
array('3')