PHP根据上一个元素删除数组重复项 [英] PHP Remove Array Duplicates Based on Previous Element

查看:80
本文介绍了PHP根据上一个元素删除数组重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建一个函数来检查数组中是否存在重复元素,并仅在重复元素与先前元素相同时才删除这些元素。让我举一个简单的例子:

I'm looking to create a function that checks an array for duplicate elements, and removes those elements only if the duplicate element is the same as the previous element. Let me give you a simple example:

以下数组(在这种情况下,该数组将不是多维的)如下:

The following array (in this case, the array will not be multi-dimensional) is as follows:

array('apple', 'apple', 'pear', 'orange', 'banana', 'apple', 'banana');

在这种情况下,删除重复数组函数将返回包含以下元素的数组:

In this case, the remove duplicate array function, would return an array with the following elements:

array('apple', 'pear', 'orange', 'banana', 'apple', 'banana');

请注意,数组中仍然存在重复项。在这种情况下,第一个和第二个元素是重复的(均为 apple),一个在另一个之前。就是说,在第一个数组中发现了三种情况的 apple,但是只删除了一个(在本例中为第二个元素),因为它是数组中前一个元素的重复。遵循这些规则,尽管存在香蕉的重复项,但由于它不是先前数组元素的重复项,因此不会将其删除。有什么好的功能的想法吗?

Note that there are still "duplicates" in the array. In case case, the first and second element, were duplicates (both "apple"), with one preceding the other. That said, there are three cases of "apple" found in the first array, but only one (in this case, the second element), was removed, because it was a duplicate of the previous element in the array. Going on those rules, while there are duplicates of "banana", since it isn't a duplicate of the previous array element, it isn't removed. Any ideas on a good function for this?

推荐答案

也许是这样的:

function remove_adjacent_dups($arr) {
  $prev = null;
  $result = array();
  foreach( $arr as $val ) {
    if( $val !== $prev ) array_push($result, $val);
    $prev = $val;
  }
  return $result;
}

这篇关于PHP根据上一个元素删除数组重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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