问题描述
我使用和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.
第一第二阵列中每个元件的频率进行计数。这给了我们一个阵列,其中键是应该从 $ A
删除和值是每个元素应该被删除的次数的元素。
然后 array_filter
用于检查的元素 $ A
逐个并删除那些应该被删除。过滤功能使用空
返回真正
,如果没有钥匙等于项被检查或如余下拆除算上该项目已经达到零; 空
的行为完全符合该法案。
这篇关于请重复使用和array_diff而的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!