views:

40

answers:

3

Hay guys, i have an array contain this data

Array
    (
    [id] => Array
        (
            [0] => 1
            [1] => 10
            [2] => 4
        )

    [age] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 2
        )
)

Now i want to remove duplicates from the ['age'] and leave the first one in tact.

So this would return

Array
    (
    [id] => Array
        (
            [0] => 1
            [2] => 4
        )

    [age] => Array
        (
            [0] => 1
            [2] => 2
        ) 
)

Any ideas? Or is there a function already in place to do this?

+1  A: 

Like Gordon said, you'd need a custom function to make the relationship but you can use http://php.net/manual/en/function.array-unique.php ?

Wouldn't it be better to have the keys of the age array the corresponding values of the id array?

ryan
Brilliant idea, then i could just grab the first item and not worry about the dupes!
dotty
A: 
<?php

$array = array(
    'id' => array(0 => 1, 1 => 10, 3 => 4),
    'age' => array(0 => 1, 1 => 1, 2 => 2)
);  

array_walk($array, 'dupe_killer');

print_r($array);

function dupe_killer(&$value, $key)
{
    $value = array_unique($value);
}

?>
joshtronic
array_walk applies the user-defined function funcname to each element of the array $array. while it is not necessary here.
Bakhtiyor
Doesn't work. Removes dupes from $ids, but doesn't then remove the same item from the $ages
dotty
array_unique() isn't recursive, how would you apply it to each element?
joshtronic
ah, i misunderstood the question. looks like an answer was found though, cheers!
joshtronic
@joshtronic. I think you need to read again the manual for array_unique();
Bakhtiyor
@bakh actually, i needed to read the question, i was way off on the whole thing
joshtronic
A: 

You could try this

$array = array('id' => array(1,10,4), 'age'=>array(1,1,2));
$age_array = array();
foreach ($array['age'] as $key => $val) {
  if (in_array($val, $age_array))
    unset($array['id'][$key], $array['age'][$key]);
  $age_array[] = $val;
}
print_r($array);

this returns Array ( [id] => Array ( [0] => 1 [2] => 4 ) [age] => Array ( [0] => 1 [2] => 2 ) )

Regards Luke

Luke