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.

1

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

I think you could return false and use array_filter.
yes, I see, but when I use array_filter I have to explain for @chhorn soro. Btw, your solution is very excellent

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.