chhorn soro chhorn soro - 7 months ago 14
PHP Question

Remove duplicates from Array based on multiple keys

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.

Answer

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