Becky
Becky

Reputation: 5585

Seperate array using array_chunk() and remove chunk duplicates

I've got an array. How can I compare vales 3 by 3 and remove if any 3 set duplicates?

This is what I tried but does not work.

$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 );

This is an example of what I'm trying to do above:

//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");

Upvotes: 0

Views: 589

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Solution using array_map, implode and explode functions:

$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);

The output:

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() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys.

Upvotes: 3

jackomelly
jackomelly

Reputation: 543

I think the point is find an "object" that makes array_unique works, and the type "array" seems not to fit. The type "string" should fit, I would try something like this:

$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);

Drawback: you have to be sure that _ is not present in any of the original string...

Upvotes: 0

Related Questions