5

if i have an array like this :

Array (
  [0]=>
  Array (
    ["id"]=> "1"
    ["desc"]=> "desc 1"
    ["type"]=> "T"
    ["date"]=> "17-JAN-12"
  )
  [1]=>
  Array (
    ["id"]=> "2"
    ["desc"]=> "desc 2"
    ["type"]=> "P"
    ["date"]=> "05-JAN-12"
  )
  [2]=>
  Array (
    ["id"]=> "1"
    ["desc"]=> "desc 3"
    ["type"]=> "P"
    ["date"]=> "15-JAN-12"
  )
  [3]=>
  Array (
    ["id"]=> "3"
    ["desc"]=> "desc 4"
    ["type"]=> "P"
    ["date"]=> "06-JAN-12"
  )
  [4]=>
  Array (
    ["id"]=> "2"
    ["desc"]=> "desc 5"
    ["type"]=> "T"
    ["date"]=> "06-JAN-12"
  )
 )

I want to remove from it the elements that has duplicate values on only the key "id" , and get :

Array (
  [0]=>
  Array (
    ["id"]=> "1"
    ["desc"]=> "desc 1"
    ["type"]=> "T"
    ["date"]=> "17-JAN-12"
  )
  [1]=>
  Array (
    ["id"]=> "2"
    ["desc"]=> "desc 2"
    ["type"]=> "P"
    ["date"]=> "05-JAN-12"
  )
  [2]=>
  Array (
    ["id"]=> "3"
    ["desc"]=> "desc 4"
    ["type"]=> "P"
    ["date"]=> "06-JAN-12"
  )
 )

Thanks.

3
  • 2
    This task is not so hard. Have you tried something? Commented Jan 19, 2012 at 9:06
  • How do you want to handle duplicates? Pick first? Average? Sum? Count? Commented Jan 19, 2012 at 9:06
  • 2
    which element you take if is duplicated ? the first Commented Jan 19, 2012 at 9:08

2 Answers 2

6
$result = array();
foreach($array as $arr){
   if(!isset($result[$arr["id"]])){
      $result[$arr["id"]] = $arr;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

2

it seems, that id is your primary key. so loop through array and insert element to new array only if id doesn't still exists.

$new_array = array();
foreach ($old_array as $entry) {
    if (empty($new_array[$entry['id']])) $new_array[$entry['id']] = $entry;
}
$new_array = array_values($new_array);

btw. the last line is only for re-order your keys in final array

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.