请重复使用和array_diff而 [英] Keep Duplicates while Using array_diff

查看:115
本文介绍了请重复使用和array_diff而的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用和array_diff()取出来的值这是在数组2中ARRAY1的。问题是它会删除所有出现在array1,作为PHP单证会注意到。我希望它只是采取了一次。

I am using array_diff() to take values out of array1 which are found in array2. The issue is it removes all occurrences from array1, as the PHP documentations makes note of. I want it to only take out one at a time.

$array1 = array();
$array1[] = 'a';
$array1[] = 'b';
$array1[] = 'a';

$array2 = array();
$array2[] = 'a';

应当只用'B'返回一个'一'和一个B的阵列,代替阵列;

It should return an array with one 'a' and one 'b', instead of an array with just 'b';

推荐答案

只是为了好玩,只是浮现在脑海的东西。将工作只要你的数组包含字符串:

Just for the fun of it, something that just came to mind. Will work as long as your arrays contain strings:

$a = array('a','b','a','c');
$b = array('a');

$counts = array_count_values($b);
$a = array_filter($a, function($o) use (&$counts) {
    return empty($counts[$o]) || !$counts[$o]--;
});

它具有的优点在于,它仅仅走到每个阵列的一次。

It has the advantage that it only walks over each of your arrays just once.

看到它在行动

See it in action.

它是如何工作:

第一第二阵列中每个元件的频率进行计数。这给了我们一个阵列,其中键是应该从 $ A 删除和值是每个元素应该被删除的次数的元素。

First the frequencies of each element in the second array are counted. This gives us an arrays where keys are the elements that should be removed from $a and values are the number of times that each element should be removed.

然后 array_filter 用于检查的元素 $ A 逐个并删除那些应该被删除。过滤功能使用返回真正,如果没有钥匙等于项被检查或如余下拆除算上该项目已经达到零; 的行为完全符合该法案。

Then array_filter is used to examine the elements of $a one by one and remove those that should be removed. The filter function uses empty to return true if there is no key equal to the item being examined or if the remaining removal count for that item has reached zero; empty's behavior fits the bill perfectly.

如果上述两个拥有那么我们想返回和减少一个去除计数。使用假|| !$计数[$ O] - 是一招,以便简洁:它递减计数和计算结果始终为,因为我们知道该计数大于零开始与(如果不是, || 会短路评估之后,空)。

If neither of the above holds then we want to return false and decrement the removal count by one. Using false || !$counts[$o]-- is a trick in order to be terse: it decrements the count and always evaluates to false because we know that the count was greater than zero to begin with (if it were not, || would short-circuit after evaluating empty).

这篇关于请重复使用和array_diff而的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆