PHP取不定個數數組交集

最近有個需求,有一個N個二維數組,N是動態的,不固定個數,現需取這N個數組的交集內容。

  • 用到的函數是array_intersect_assoc
  • 用法
$result_arr = array_intersect_assoc($arr_sourse[0],$arr_sourse[1],.......$arr_sourse[N-1]);
  • 數組內容
$arr1 = ["16","2","3","6","9","17"];
    $arr2 = ["16","2","3","9","15"];
    $arr3 = ["16","2","3","6","8","17"];

固定數組的用法

$diff = array_intersect($arr1,$arr2,$arr3);
    echo '<pre>';
    print_r($diff);// ["16","2","3"]

不固定數組用法

  • 只需用 call_user_func_array 來執行 array_intersect_assoc 就能夠了
  • 具體用法
$result_array = call_user_func_array ('array_intersect_assoc', array($arr1, $arr2,$arr3));
    echo '<pre>';
    print_r($result_array);// ["16","2","3"]
相關文章
相關標籤/搜索