1

I have an array structure like the following:

Array
(
    [0] => Array
        (
            [title] => Blue
            [image] => catalog/Color/blue.png
        )
    [1] => Array
        (
            [title] => Black
            [image] => catalog/Color/black.png
        )
    [2] => Array
        (
            [title] => Black
            [image] => catalog/Color/black.png
        )
)

What I want to do is to remove duplicate element from array. I have tried to use array_unique($myarray), but it seem not working.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
chhorn soro
  • 199
  • 1
  • 3
  • 13
  • In addition to the dupe, [array_unique($array, SORT_REGULAR);](https://stackoverflow.com/a/18373723/2943403) will work for this sample data. – mickmackusa May 20 '22 at 03:29

2 Answers2

6

Just use the title and image combined as the keys and it will insure uniqueness:

foreach($array as $val) {
    $result[$val['title'].$val['image']] = $val;
}
// if you want, get values and reindex
$result = array_values($result);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
4

Try my solution:

<?php
function searchDuplicate($arr, $obj) {
    foreach ($arr as $value) {
        if ($value['title'] == $obj['title'] && $value['image'] == $obj['image']) {
            return true; //duplicate
        }
    }
    return false;
};

$arr = array(
    array (
            'title' => 'Blue',
            'image' => 'catalog/Color/blue.png'
        ),
    array (
            'title' => 'Black',
            'image' => 'catalog/Color/black.png'
        ),
     array (
            'title' => 'Black',
            'image' => 'catalog/Color/black.png'
        )
);

$result = array();
foreach ($arr as $obj) {
    if (searchDuplicate($result, $obj) === false) {
        $result[] = $obj;
    }
}

print_r($result);
Thi Tran
  • 681
  • 5
  • 11