Alfred Forsinger
Alfred Forsinger

Reputation: 1

How to remove duplicate values for specific key in multi-dimentional array?

I have the following multi-dimentional array:

<?php 
$array = array(
array('first' => 1, 'second' => 1),
array('first' => 1, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1),
array('first' => 3, 'second' => 1),
array('first' => 3, 'second' => 1));

How can I remove the duplicate first values? While preserving the duplicate second values.

After processing the array should be:

array(
array('first' => 1, 'second' => 1),
array('first' => 2, 'second' => 1),
array('first' => 3, 'second' => 1));

See: http://codepad.org/tMh28KMf

Upvotes: 0

Views: 416

Answers (4)

Parag
Parag

Reputation: 4812

what if the array is like this

$array = array(
    array('first' => 1, 'second' => 1),
    array('first' => 1, 'second' => 1),
    array('first' => 1, 'second' => 12),
    array('first' => 2, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
    array('first' => 3, 'second' => 1)
);

$temp = array();
$new = array();

You want new array $new contains the following:

array(
    array('first' => 1, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
);

or

array(
    array('first' => 1, 'second' => 1),
    array('first' => 1, 'second' => 12),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
);

?

Upvotes: 0

Anne
Anne

Reputation: 27073

Code:

$array = array(
    array('first' => 1, 'second' => 1),
    array('first' => 1, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
    array('first' => 3, 'second' => 1)
);

$temp = array();
$new = array();

foreach($array as $value)
{
    if(!in_array($value['first'],$temp))
    {
        $temp[] = $value['first'];
        $new[] = $value;
    } 
}

Now $new contains the following:

array(
    array('first' => 1, 'second' => 1),
    array('first' => 2, 'second' => 1),
    array('first' => 3, 'second' => 1),
);

Upvotes: 1

user925885
user925885

Reputation:

This removes the duplicate arrays:

$array = array_map('unserialize', array_unique(array_map('serialize', $array)));

The keys are still the same so you might need to fix them.

Upvotes: 0

curtisdf
curtisdf

Reputation: 4210

You'll have to do some foreach loops and reassemble the array yourself. Check out PHP's array_unique() too.

Upvotes: 0

Related Questions