Php - removing elements from an array that has duplicate values ​​for the specified key

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 elements from it that have duplicate values ​​only for the id key, 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"
  )
 )

Thank.

+5
source share
2 answers
$result = array();
foreach($array as $arr){
   if(!isset($result[$arr["id"]])){
      $result[$arr["id"]] = $arr;
   }
}
+6
source

seems to be idyour primary key. therefore, loop the array and insert the element into the new array only if it iddoes not exist.

$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);

by the way. the last line is only for reordering your keys in the final array

+2
source

All Articles