我有一个数组
array:2 [▼
0 => array:2 [▼
0 => 159
1 => 158
]
1 => array:2 [▼
0 => 159
1 => 158
]
2 => array:2 [▼
0 => 158
1 => 159
]
]
我想按相反的顺序删除重复的和重复的。例如,索引0
和索引1
具有相同的值159 and 158
,其顺序也与0 => 159
和1 => 158
相同。我想删除索引1
或0
。既然是一样的。如果你注意到索引2
。它具有相同的值,唯一的区别是顺序CCD_ 9和CCD_。如果该数组是$remove_arr
,我该怎么做
因此,由于我将删除索引2
和索引0
或1
,因此应该只剩下一个索引。
这里有一个较短的解决方案:
$data = [[158, 159], [158, 159], [159, 158]];
$unique = array_unique(array_map(function ($item) {
sort($item); return $item;
}, $data), SORT_REGULAR);
dump($unique); // This will output [[158, 159]]
此解决方案对级别2数组的内容进行排序。因此,排序后,最后一个值也将变为[158, 159]
,因此它可以被array_unique
正确地评估为重复值。
count(array_entersect())获取数组中相同项的数量。当它等于阵列长度时,移除其中一个
$remove_arr = [
[158, 159],
[158, 159],
[159, 158]
];
for($i = count($remove_arr)-1; $i >= 0 ; $i--) {
$j = $i-1;
while ($j >= 0) {
if (count(array_intersect($remove_arr[$i],$remove_arr[$j])) == count($remove_arr[$i]))
{ unset($remove_arr[$i]); break; }
else $j--;
}
}
print_r($remove_arr);