一旦更多关于PHP中的多维数组删除重复值 [英] Once more about removing duplicate values from a multi-dimensional array in PHP
问题描述
在经过辛苦的搜索,我发现像我想解决一些类似的问题,但我不能用自己的答案。
After an exhausting search I found some similar problems like the one I would like to solve, but I could not use their answers.
海尔一些很好的例子:
<一个href=\"http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php\">How从PHP中多维数组中删除重复值
How to remove duplicate values from a multi-dimensional array in PHP
<一个href=\"http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php\">How从PHP中多维数组中删除重复值
How to remove duplicate values from a multi-dimensional array in PHP
<一个href=\"http://stackoverflow.com/questions/22139377/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php-revisited\">How从PHP中的多维数组删除重复值重新
这一个是最相似的,但答案不知何故不工作我了。
This one is the most similar, but the answer somehow doesn't work to me.
<一个href=\"http://stackoverflow.com/questions/22001121/php-filter-array-values-and-remove-duplicates-from-multi-dimensional-array\">php滤镜阵列值并从多维数组复制
我的问题的主要区别是,当人们正在寻找一个解决方案,以从阵列中删除整个复制子阵,我试图删除子阵只有一个$键=> $ value对的子阵列是类似记者对另一子数组。其它对可以具有不同的值或者甚至相同。
The main difference to my issue is that while people are looking for a solution to delete an entire duplicated subarray from the array, I'm trying to delete the subarray when only one $key => $value pair of the subarray is similar to the correspondent pair of another subarray. The other pairs could have different values or even the same.
下面我的数组:
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
)
我怎么能设法删除这些子阵,所以我有以下结果:
How could I manage to delete these subarrays so I have following result:
Array(
[0] => Array
(
[0] => AAA
[1] => 500
)
[1] => Array
(
[0] => BBB
[1] => 500
)
[2] => Array
(
[0] => CCC
[1] => 820
)
提前感谢!
推荐答案
最简单的方法(在我看来),而不是使用神奇的 array_filter
和 array_map
手工艺是难以维持,是写一个专门的功能自己:
The easiest solution (in my opinion), instead of using magical array_filter
and array_map
handicraft which is difficult to maintain, is to write a specialized function yourself:
$out = [];
$usedKeys = [];
foreach ($in as $element)
{
list ($a, $b) = $element;
if (!isset($usedKeys[$a]))
{
$usedKeys[$a] = true;
$out[]= $element;
}
}
var_dump($out);
这将只返回元素的第一对元素独特的(以第一位的,如果多个条目可用)。
This will return only elements whose first pair element is unique (taking first one, if multiple entries are available).
这篇关于一旦更多关于PHP中的多维数组删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!