PHP陣列去重後返回陣列包物件給前端
阿新 • • 發佈:2021-08-09
/** * @return array * 1、陣列去重返回給前端(foreach迴圈) * 優點:可判斷多個去重條件 */ public function admin() { $arr = array( ['id' => 1, 'name' => 'PHP'], ['id' => 5, 'name' => 'JAVA'], ['id' => 2, 'name' => 'PYTHON'], ['id' => 4, 'name' => 'VUE'], ['id' => 1, 'name' => 'PHP'] ); foreach ($arr as $key => $val) { foreach ($arr as $k => $v) { if ($key != $k && $val['name'] == $v['name'] && $val['id'] == $v['id']) unset($arr[$key]); } } return array_merge([], $arr); } /** * @return array * 2、陣列去重返回給前端(PHP函式) * 缺點:去重條件只能一個 */ public function admin2() { $arr = array( ['id' => 1, 'name' => 'PHP'], ['id' => 5, 'name' => 'JAVA'], ['id' => 2, 'name' => 'PYTHON'], ['id' => 4, 'name' => 'VUE'], ['id' => 1, 'name' => 'PHP'] ); /** * @param1 陣列 * @param2 null * @param3 去重的欄位 */ $data = array_column($arr,null,'name'); //array_values 返回陣列的所有值(非鍵名) return array_values($data); }