僅支援一維陣列,多維陣列直接使用會觸發 Array to string conversion 警告且無法正確比較。
1, 'name' => 'A'], ['id' => 2, 'name' => 'B'], ['id' => 1, 'name' => 'A'], // 重複 ]; print_r(array_unique_multi($data)); /* 保留第一個出現的,鍵名保留原索引 */
$val) { $temp[$key] = $assoc ? json_encode($val, JSON_UNESCAPED_UNICODE) : implode(',', $val); } // 去重 $temp = array_unique($temp); // 還原 $result = []; foreach ($temp as $key => $val) { $result[$key] = $assoc ? json_decode($val, true) : explode(',', $val); } return $keepKeys ? $result : array_values($result); } // 測試 $data = [ 'first' => ['title' => '1111', 'date' => '2222'], 'second' => ['title' => '1111', 'date' => '2222'], // 重複 'third' => ['title' => '2222', 'date' => '3333'], ]; print_r(unique_arr($data, true, true)); /* 保留 first、third,鍵名保留 */
$value) { if (!in_array($value, $out, true)) { $out[$key] = $value; } } return $out; }
| 方法 | 耗時 | 記憶體 | 備註 |
|---|---|---|---|
| serialize/unserialize | ~1.2s | 高 | 通用、處理任意結構 |
| json_encode/array_unique | ~0.8s | 中 | 推薦,JSON 可讀、效能佳 |
| implode/array_unique | ~0.6s | 低 | 僅限索引陣列、值無逗號 |
true 給保留鍵名參數。DISTINCT 或 Redis Set 去重。多維陣列去重核心思路:降維為字串 → array_unique → 還原。推薦 json_encode 方案平衡通用性、效能與可讀性。封裝為工具函數 unique_arr() 專案複用。