使用array_chunk()分隔数组并删除chunk duplicates

时间:2016-04-14 08:45:56

标签: php

我有一个阵列。如何比较3到3的值,如果有3个重复,则删除?

这是我尝试但不起作用。

$arr = array("bmw","white","class A", "mazda","red","demio", "Honda","maroon","vezel", "bmw","white","class A");
$chunks = array_chunk($arr,3);
$finalArr = array_unique( $chunks );

这是我在上面尝试做的一个例子:

//original array
$arr = ("bmw","white","class A", "mazda","maroon","class A", "Honda","maroon","vezel", "bmw","white","class A");

//separated array values to 3 by 3 sets
 "bmw",   "white",   "class A"
 "mazda", "maroon",  "class A"
 "Honda", "maroon",  "vezel"
 "bmw",   "white",   "class A"

//Removing 3set duplicates and expected new array:
$finalArr = ("bmw","white","class A", "mazda","maroon","class A", "Honda","maroon","vezel");
  • 我正在寻找一种方法来删除块重复(3个匹配集)。没有重复。

2 个答案:

答案 0 :(得分:3)

使用array_mapimplodeexplode函数的解决方案:

$arr = array("bmw","white","class A", "mazda","red","demio", "Honda","maroon","vezel", "bmw","white","class A");
$chunks = array_chunk($arr,3);
$uniqueArr = array_unique(array_map(function($v){ return implode(",",$v);  },$chunks));
$finalArr = array_map(function($v){ return explode(",",$v);  },$uniqueArr);

print_r($finalArr);

输出:

Array
(
    [0] => Array
        (
            [0] => bmw
            [1] => white
            [2] => class A
        )

    [1] => Array
        (
            [0] => mazda
            [1] => red
            [2] => demio
        )

    [2] => Array
        (
            [0] => Honda
            [1] => maroon
            [2] => vezel
        )
)
  

array_unique()首先对作为字符串处理的值进行排序,然后保留每个值遇到的第一个键,并忽略所有值   以下钥匙。

答案 1 :(得分:0)

我认为重点是找到一个"对象"使array_unique有效,类型"数组"似乎不合适。类型"字符串"应该适合,我会尝试这样的事情:

$a0 = array_chunk($arr,3);
//
$a1 = array();
foreach ($a0 as $r) $a1[]= implode('_', $r);
//
$a2 = array_unique($a1);
//
$final = array();
foreach ($a2 as $r) $final[]= explode('_', $r);

缺点:你必须确保任何原始字符串中都没有_ ......