我有一个看起来像这样的数组
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
最后我希望数组看起来像这样
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
带有SORT_REGULAR标志的array_unique检查所有三个值。我已经看到了一些关于如何根据一个值删除重复项的解决方案,但我需要比较前两个值的唯一性。
答案 0 :(得分:3)
使用foreach
循环和array_values
函数的简单解决方案:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
输出:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
答案 1 :(得分:0)
带注释的示例代码:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
答案 2 :(得分:0)
为了好玩。这将保留最后一次出现并消除其他事件:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
如果你想保留第一次出现,那么只需在之前和之后反转数组:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));