PHP array_intersect, call_user_func_array 教學筆記

最近因為工作需求所以使用了array_intersect,因此特別將這個涵式的使用情境與用法寫成筆記,方便有需要的人可以查看

array_intersect ( array $array1 , array $array2 [, array $... ] ) : array
功能簡介:從多個陣列中找出交集
使用情境:校長想要找出 1班、2班、3班中皆有的共同有興趣課程
$class1 = array("國文", "英文", "數學");
$class2 = array("國文", "英文", "自然");
$class3 = array("國文", "體育");
$result = array_intersect($class1, $class2, $class3);
print_r($result);

Result:
Array ( [0] => 國文 )
三個班級中,共同都有興趣的課程是 國文
特別情況
帶入 array_intersect 的陣列參數數量可能是會變動的,以上面的使用情境來說就是,我可能帶入三個陣列來取得交集 (class1, class2, class3),也有可能在某些情況下只會帶入兩個陣列來取得交集 (class1, class2),這個時候需要動態調用函數,如果是以上狀況可以參考下面做法:
1. 先宣告一個陣列 (ex: $all_class),然後迴圈放置需要交集的陣列於內
$all_class = [$class1, $class2, $class3, …..$classN];
2. 使用 call_user_func_array 這樣就可以完成了
$result = call_user_func_array('array_intersect', $all_class);
其他更多精彩的分享

生活攻略站長

我是 Hank!,我是網站工程師,也是一位生活玩家,這是我的部落格,分享 生活知識、旅遊紀錄、開箱心得、網站架設筆記


My name is Hank, this blog shares Knowledge of life, Travel records and Website setup notes, hope you will like it