騰云網(wǎng)絡(luò) PHP數(shù)組 并集 交集 差集
2021-04-19
來源:www.cnblogs.com/whyly/p/13563634.html
1.并集
array_merge
字符串鍵名相同,后面覆蓋前面,數(shù)字鍵名會(huì)在后面追加,不覆蓋,參考代碼如下
$array1 = array("color" => "red", 2, 4);$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);$result = array_merge($array1, $array2);print_r($result);
結(jié)果
Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )
如果鍵名都是數(shù)字的話,后面的數(shù)組元素會(huì)追加到前面數(shù)組之后,并重建索引
$array1 = array(1 => 2, 2 => 4, 3 => 6);$array2 = array(1 => 1, 2 => 3, 3 => 5);$result = array_merge($array1, $array2);print_r($result);
結(jié)果
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 1 [4] => 3 [5] => 5 )
使用+運(yùn)算符
使用+運(yùn)算符合并數(shù)組,會(huì)保留前面數(shù)組的鍵名,后面數(shù)組元素會(huì)追加到前面數(shù)組后面,并且鍵名相同時(shí),是前面覆蓋后面。
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');$result = $array1 + $array2;print_r($result);
結(jié)果
Array ( [0] => zero_a [2] => two_a [3] => three_a [1] => one_b [4] => four_b )
2.交集
array_intersect
第一個(gè)數(shù)組是主值,返回有相同元素的值(判斷依據(jù)是元素字符串相同,即 (string) $elem1 === (string) $elem2),鍵值保留第一個(gè)元素的鍵值
$array1 = array("a" => "green", "red", "blue");$array2 = array("b" => "green", "yellow", "red");$result = array_intersect($array1, $array2);print_r($result);
結(jié)果
Array ( [a] => green [0] => red )
array_intersect_assoc
array_intersect_assoc不僅檢查元素值,還會(huì)檢查鍵名,都相同的元素才會(huì)保留下來,鍵值對(duì) key => value 中的兩個(gè)值僅在 (string) $elem1 === (string) $elem2 時(shí)被認(rèn)為相等
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red", 100 => 'a100');$array2 = array("a" => "green", "b" => "yellow", "blue", "red", '100' => 'a100');$result_array = array_intersect_assoc($array1, $array2);print_r($result_array);
結(jié)果
Array ( [a] => green [100] => a100 )
3.差集
array_diff
返回前面數(shù)組有而后面沒有的元素?cái)?shù)組,保留前面元素的鍵名,相同判斷是根據(jù)字符串值相同,即 (string) $elem1 === (string) $elem2
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
結(jié)果
Array ( [1] => blue )
array_diff_assoc
array_diff_assoc不僅檢查元素,還檢查鍵名,鍵值對(duì) key => value 中的兩個(gè)值僅在 (string) $elem1 === (string) $elem2 時(shí)被認(rèn)為相等
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");$array2 = array("a" => "green", "yellow", "red");$result = array_diff_assoc($array1, $array2);print_r($result);
結(jié)果
Array ( [b] => brown [c] => blue [0] => red )
再來個(gè)例子
$array1 = array(0, 1, 2);$array2 = array("00", "01", "2");$result = array_diff_assoc($array1, $array2);print_r($result);
結(jié)果
Array ( [0] => 0 [1] => 1 )
簡單分享快樂學(xué)習(xí),如有錯(cuò)誤請多包涵!
PS:如果沒有你的關(guān)注,那我所做的將毫無意義!歡迎分享,點(diǎn)贊,在看。