使用 array_diff 时保持重复 [英] Keep Duplicates while Using array_diff

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

问题描述

我正在使用 array_diff() 从 array2 中找到的 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';

它应该返回一个包含一个'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 中删除的元素,值是每个元素应该被删除的次数.

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中的元素进行一一检查,去掉那些应该去掉的元素.过滤器函数使用 empty 返回 true 如果没有与正在检查的项目相同的键或者该项目的剩余删除计数已达到零;empty 的行为完全符合要求.

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.

如果以上都不成立,那么我们要返回 false 并将删除计数减一.使用 false ||!$counts[$o]-- 是一种简洁的技巧:它递减计数并始终评估为 false 因为我们知道计数开始时大于零with(如果不是,|| 会在评估 empty 后短路).

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天全站免登陆