经过艰苦的搜索后,我发现了一些类似的问题,比如我想要解决的问题,但我无法使用他们的答案。
Hier是一些非常好的例子:
How to remove duplicate values from a multi-dimensional array in PHP
How to remove duplicate values from a multi-dimensional array in PHP
How to remove duplicate values from a multi-dimensional array in PHP revisited
这个是最相似的,但答案对我来说不起作用。
php filter array values and remove duplicates from multi dimensional array
我的问题的主要区别在于,虽然人们正在寻找从阵列中删除整个重复子阵列的解决方案,但我只是在只有一个$ key =>时尝试删除子阵列。该子阵列的$ value对类似于另一个子阵列的对应对。其他对可以有不同的值,甚至可以是相同的。
这是我的数组:
Array(
[0] => Array
(
[0] => AAA
[1] => 500
)
[1] => Array //Won't be delete 'cause [0] is different, although [1] is the same.
(
[0] => BBB
[1] => 500
)
[2] => Array //Will be delete 'cause [0] is the same.
(
[0] => AAA
[1] => 500
)
[3] => Array //Won't be delete 'cause [0] is different.
(
[0] => CCC
[1] => 820
)
[4] => Array
(
[0] => AAA //Will be delete 'cause [0] is the same. [1] is also different.
[1] => 774
)
如何设法删除这些子数组,以便得到以下结果:
Array(
[0] => Array
(
[0] => AAA
[1] => 500
)
[1] => Array
(
[0] => BBB
[1] => 500
)
[2] => Array
(
[0] => CCC
[1] => 820
)
非常感谢提前!
答案 0 :(得分:0)
最简单的解决方案(在我看来),而不是使用难以维护的神奇的array_filter
和array_map
手工艺品,是自己编写一个专门的功能:
$out = [];
$usedKeys = [];
foreach ($in as $element)
{
list ($a, $b) = $element;
if (!isset($usedKeys[$a]))
{
$usedKeys[$a] = true;
$out[]= $element;
}
}
var_dump($out);
这将只返回第一对元素是唯一的元素(如果有多个条目可用,则取第一个元素)。
答案 1 :(得分:0)
这对我有用(根据提供的链接):
<?php
$items = array(
array(
0 => 'AAA',
1 => 500,
),
array(
0 => 'BBB',
1 => 500,
),
array(
0 => 'AAA',
1 => 500,
),
array(
0 => 'CCC',
1 => 820,
),
array(
0 => 'AAA',
1 => 774,
),
);
$taken = array();
foreach($items as $key => $item) {
if(!in_array($item[0], $taken)) {
$taken[] = $item[0];
} else {
unset($items[$key]);
}
}
echo '<pre>'.print_r($items,true).'</pre>';