Skip to content
Advertisement

Remove duplicate combination of elements from multidimensional array

I have an array with fields:

$products = array(
    [0] => array('name' => 'product_one', 'category' => 'category_one', employee => '3234'),
    [1] => array('name' => 'product_two', 'category' => 'category_two', employee => '5421'),
    [2] => array('name' => 'product_three', 'category' => 'category_one', employee => '3234'),
    [3] => array('name' => 'product_one', 'category' => 'category_one', employee => '2153'),
    [4] => array('name' => 'product_one', 'category' => 'category_two', employee => '6312')        
)

Now, in this case, employee field is not important, but the combination of product/category is unique.

Wanted result:

$products = array(
    [0] => array('name' => 'product_one', 'category' => 'category_one', employee => '3234'),
    [1] => array('name' => 'product_two', 'category' => 'category_two', employee => '5421'),
    [2] => array('name' => 'product_three', 'category' => 'category_one', employee => '3234'),
    [4] => array('name' => 'product_one', 'category' => 'category_two', employee => '6312')        
)

Any idea what is the best way to do this? On production, I have more than 30.000 elements and usually around 10 duplicates. Also in real database, I have 12 fields and a combination of 4 of them needs to be unique).

Advertisement

Answer

If you don’t mind which of the duplicates you keep, it’s probably simplest to iterate over the loop, making a new array with keys which are a combination of the required unique values (I’ve used a separator of ## in this code, you can use anything that cannot occur in the values). This way duplicates will be automatically removed as an array cannot have identical keys. Once the loop is done the output array can be re-indexed numerically using array_values:

$output = array();
foreach ($products as $p) {
    $output["{$p['name']}##{$p['category']}"] = $p;
}

$output = array_values($output);
print_r($output);

Output (for your sample data):

Array
(
    [0] => Array
        (
            [name] => product_one
            [category] => category_one
            [employee] => 2153
        )
    [1] => Array
        (
            [name] => product_two
            [category] => category_two
            [employee] => 5421
        )
    [2] => Array
        (
            [name] => product_three
            [category] => category_one
            [employee] => 3234
        )
    [3] => Array
        (
            [name] => product_one
            [category] => category_two
            [employee] => 6312
        )
)

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement