方法#1:foreach
循環與isset()
通過他們的第一次出現那種值(Demo)
(*此方法似乎是最快的所有的)
$array=[[8,9,7],[7,8,9,33,21],[11,12,33,21,9,31]];
foreach($array as $sub){
foreach($sub as $v){
if(!isset($result[$v])){ // only add first occurence of a value
$result[$v]=$v;
}
}
}
var_export(array_values($result)); // re-index and print to screen
// condensed output: array(8,9,7,33,21,11,12,31)
方法#2:分配臨時密鑰強制覆蓋值以確保沒有重複(Demo)
$array=[[8,9,7],[7,8,9,33,21],[11,12,33,21,9,31]];
foreach($array as $sub){
foreach($sub as $v){
$result[$v]=$v; // force overwrite because duplicate keys cannot occur
}
}
sort($result); // sort and re-index
var_export($result); // print to screen
// condensed output: array(7,8,9,11,12,21,31,33)
方法#3:array_merge()
與splat operator
和array_unique()
(Demo)
$array=[[8,9,7],[7,8,9,33,21],[11,12,33,21,9,31]];
$unique=array_unique(array_merge(...$array)); // merge all subarrays
sort($unique); // sort and re-index
var_export($unique); // print to screen
// condensed output: array(7,8,9,11,12,21,31,33)
方法#4:非正統json_encode()
& preg_match_all()
(Demo)(Pattern Demo)
$array=[[8,9,7],[7,8,9,33,21],[11,12,33,21,9,31]];
$unique=preg_match_all('~\b(\d+)\b(?!.*\b\1\b)~',json_encode($array),$out)?$out[0]:[];
sort($unique); // sort and re-index
var_export($unique); // print to screen
// condensed output: array(7,8,9,11,12,21,31,33)
這乾淨呃比接受的答案。 PLUS1 – mickmackusa