此次在項目中使用 array_diff
函數被坑了. 有以下兩個二維數組:php
$ary1 = array( array('uid'=>1,'name' => "zhangsan1"), array('uid'=>2,'name' => "zhangsan2"), array('uid'=>3,'name' => "zhangsan3"), array('uid'=>4,'name' => "zhangsan4"), ); $ary2 = array( array('uid'=>3,'name' => "zhangsan2"), array('uid'=>4,'name' => "zhangsan3"), );
求這兩個數組的差集, 用 array_diff()
函數:數組
$ary3 = array_diff($ary1, $ary2); var_dump($ary3);
輸出結果爲array(0) {}
, 哈哈, 是否是很坑啊.函數
若是用在一維數組上, 也只比較了值, 並無比較鍵, 也就是說只要值是同樣的, 就會被剔除掉, 而無論鍵是否同樣, 例如:ui
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $a2=array("e"=>"red","f"=>"black","g"=>"purple"); $a3=array("a"=>"red","b"=>"black","j"=>"yellow"); $result=array_diff($a1,$a2,$a3); print_r($result);
輸出結果爲:Array ( [b] => green [c] => blue )
code
若是要鍵也參與比較則須要使用 array_diff_assoc()
函數class