1

I have an array like this.

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [name] => abc
                    [age] => 21

                )

            [1] => Array
                (
                   [id] => 456
                   [name] => abc
                   [age] => 25
                  )
             [2] => Array
                (
                   [id] => 789
                   [name] => ghi
                   [age] => 40
                  )
               )
             )

what i want to do is find any duplicates name in that array and place that in a new array.So finally my array have to be like this.

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [name] => abc
                    [age] => 21

                )

             [1] => Array
                (
                   [id] => 789
                   [name] => ghi
                   [age] => 40
                  )
           )
     [1] => Array
        (
            [0] => Array
                (
                   [id] => 456
                   [name] => abc
                   [age] => 25

           )
         )

             )

I'm struggling on how to do that.can any body pls help me to fix this?

2
  • What have you tried? You need to loop over the array (foreach), get each name and compare to all other names using a nested loop. Commented Jul 7, 2014 at 23:07
  • I'm new to multidimentional array and can loop through the array and can acess values after that how can i process? Commented Jul 8, 2014 at 0:36

1 Answer 1

1

You can just use a simple foreach for this, you could just push the duplicate array to the next dimension if it sees one. Example:

$values = array(
    array(
        array('id' => 123, 'name' => 'abc', 'age', 21),
        array('id' => 456, 'name' => 'abc', 'age', 25),
        array('id' => 789, 'name' => 'ghi', 'age', 40),
    ),
);

foreach($values as $batch) {
    $temp = array();
    foreach($batch as $key => $value) {
        if(!isset($temp[$value['name']])) {
            $temp[$value['name']] = $value; // temporary storage
        } else {
            unset($batch[$key]);
            $values[][] = $value; // push it outside this batch
        }
    }
}

echo '<pre>';
print_r($values);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.