我有2个日期数组。我需要最有效的方法来构建第三个日期数组,其中只包含2个日期数组中相同的日期。
例如:
List of Dates #1:
2017-01-01
2017-01-02
2017-01-03
2017-02-01
2017-02-02
2017-09-09
List of Dates #2:
2017-01-01
2017-02-01
2017-03-01
2017-04-01
So array 3 should be:
2017-01-01
2017-02-01
答案 0 :(得分:2)
您正在寻找array_intersect:
$array1 = array("2017-01-01", "2017-01-01" ,"2017-01-02","2017-01-03","2017-02-01", "2017-02-02","2017-09-09");
$array2 = array("2017-01-01","2017-02-01","2017-03-01","2017-04-01");
$result = array_intersect(array_unique($array1), $array2);
echo "<pre>";
print_r($result);
输出:
Array
(
[0] => 2017-01-01
[3] => 2017-02-01
)
注意强>
array_intersect
返回包含所有值的数组$array1
,其值存在于所有参数中。所以,如果你的$array1
具有重复数据,然后结果数组也有 重复值。
我已添加array_unique来克服这种情况。
答案 1 :(得分:0)
也许 array_intersect()?
$array1 = array ("a" => "green", "red", "blue");
$array2 = array ("b" => "green", "yellow", "red");
$result = array_intersect ($array1, $array2);
结果
Array
(
[a] => green
[0] => red
)
答案 2 :(得分:0)
试试这个
function myfunction($a,$b)
{
if ($a===$b)
{
return 0;
}
return ($a>$b)?1:-1;
}
$a1=array("a"=>"red","b"=>"green","c"=>"blue","yellow");
$a2=array("A"=>"red","b"=>"GREEN","yellow","black");
$a3=array("a"=>"green","b"=>"red","yellow","black");
$result=array_uintersect($a1,$a2,$a3,"myfunction");
print_r($result);
结果:
Array ( [a] => red [0] => yellow )