PHP數(shù)組的交集array-intersect()
求兩個(gè)數(shù)組的交集問(wèn)題可以使用array_intersect(),array_inersect_assoc,array_intersect_key來(lái)實(shí)現(xiàn),其中array_intersect()函數(shù)是求兩個(gè)數(shù)的交集,就跟隨百分網(wǎng)小編一起去了解下吧,想了解更多相關(guān)信息請(qǐng)持續(xù)關(guān)注我們應(yīng)屆畢業(yè)生考試網(wǎng)!
返回一個(gè)交集共有元素的數(shù)組(只是數(shù)組值得比較)、array_intersect_assoc()函數(shù)是將鍵值和值綁定,一起比較交集部分、array_intersect_key()函數(shù)是將兩個(gè)數(shù)組的鍵值進(jìn)行比較,返回鍵值交集的數(shù)組。
(相關(guān)資料圖)
但實(shí)際應(yīng)用中也遇到了一些小問(wèn)題,正如下:
實(shí)例:
復(fù)制代碼 代碼如下:
$array = array("red"=>"Red","green"=>"red4","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz1"=>"art","peak"=>158);
$array1 = array("red"=>"Red2","greena"=>"red","Red15"=>"Red",7=>"Level","Width"=>"Red","azzzz"=>"art","peak"=>158);
$num = array_intersect($array,$array1);
print_r ($num);
echo "
";
$num = array_intersect_assoc($array,$array1);
print_r($num);
echo "
";
$num = array_intersect_key($array,$array1);
print_r ($num);
?>
運(yùn)行結(jié)果:
復(fù)制代碼 代碼如下:
Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [azzzz1] => art [peak] => 158 )
Array ( [Red15] => Red [7] => Level [Width] => Red [peak] => 158 )
Array ( [red] => Red [Red15] => Red [7] => Level [Width] => Red [peak] => 158 )
總結(jié):
1.array_intersect()函數(shù)進(jìn)行的比較只有數(shù)組值的比較,而且存在如”Red“和”Red2“比較時(shí)會(huì)返回"Red",反之則不會(huì)返回"Red2";
2.array_intersect_assoc()函數(shù)是將數(shù)組的值與鍵值一起比較,而且不會(huì)存在array_intersect的`情況,適用于較嚴(yán)格的比較;
3.array_intersect_key()函數(shù)適用于比較兩個(gè)數(shù)組鍵值的交集,返回的并不只有鍵值,而是鍵值和對(duì)應(yīng)的數(shù)組值。
詞條內(nèi)容僅供參考,如果您需要解決具體問(wèn)題
(尤其在法律、醫(yī)學(xué)等領(lǐng)域),建議您咨詢相關(guān)領(lǐng)域?qū)I(yè)人士。