Jimmy
Jimmy

Reputation: 19

Remove Duplicates in an array

I am trying to remove duplicate values from my array, the below array is what I need to alter:

Array
(
[0] => Array
    (
        [brand] => Array
            (
                [milestone] => Milestone
            )
    )

[1] => Array
    (
        [brand] => Array
            (
                [axis] => Axis
                [milestone] => Milestone
            )
    )

[2] => Array
    (
        [brand] => Array
            (
                [axis] => Axis
            )
    )

)

The end result should be this:

Array
(
[0] => Array
    (
        [axis] => Axis
    )
[1] => Array
    (
        [milestone] => Milestone
    )
)

This is what i have at the moment but it won't work.

foreach( $out_product_brands as $p_brands )
{
    foreach( $p_brands as $brands )
    {
        $brand[] = $brands;
    }
}
print_r($brand);

Could I get some help please.

Upvotes: 0

Views: 48

Answers (1)

Anatoliy R
Anatoliy R

Reputation: 1789

If you want to remove duplicate keys, this is the code you need:

$allKeys = [];
$result = [];

foreach($brand as $index => $rec) {
    $newRec = []
    foreach($rec['brand'] as $key => $val) {
        if(!isset($allKeys[$key])) {
            $newRec[$key] = $val;
            $allKeys[$key] = $val;
        }
    }
    if(count($newRec)) {
        $result[] = $newRec;
    }
}

If you want to remove only value duplicates this is more complicated, you need to specify logic - what to do with duplicate keys with different values.

Upvotes: 1

Related Questions