Removing similar elements from PHP array

I have an array structured like this:

$arrNames = array(

array('first'=>'John', 'last'=>'Smith', 'id'=>'1'),
array('first'=>'John', 'last'=>'Smith', 'id'=>'2'),
array('first'=>'John', 'last'=>'Smith', 'id'=>'3')

)

      

I need to remove similar items where fist and last name are the same. I usually use array_unique, but the elements are not unique as each has a unique ID. I don't care which ID is stored. I just need an array to look like this:

$arrNames = array(

array('first'=>'John', 'last'=>'Smith', 'id'=>'1') // can be any id from the original array

)

      

Is there a quick way to do this? My first thought is to use something like bubble sort, but I'm wondering if there is a better (faster) way. The resulting array is added to the dropdown and duplicate entries confuse some users. I am using an id to pull a record from the db after it is selected. Therefore, it must be included in the array.

+3


source to share


2 answers


<?php

  $arrNames = array(
    array('first'=>'John', 'last'=>'Smith', id=>'1'),
    array('first'=>'John', 'last'=>'Smith', id=>'2'),
    array('first'=>'John', 'last'=>'Smith', id=>'3')
  );

  $arrFound = array();
  foreach ($arrNames as $intKey => $arrPerson) {
    $arrPersonNoId = array(
      'first' => $arrPerson['first'],
      'last' => $arrPerson['last']
    );
    if (in_array($arrPersonNoId, $arrFound)) {
      unset($arrNames[$intKey]);
    } else {
      $arrFound[] = $arrPersonNoId;
    }
  }
  unset($arrFound, $intKey, $arrPerson, $arrPersonNoId);

  print_r($arrNames);

      

It definitely works, be it the best way to discuss ...



Codepad

+6


source


There is not a quick and easy way that I know of, but here is a relatively simple way to do it, assuming the ids for "similar items" do not matter (ie you only need the period of the identifier).

$final = array();
foreach ($array as $values) {
   $final[$values['first'] . $values['last']] = $values;
}
$array = array_values($final);

      



The last step is not strictly necessary .. only if you want to remove derived keys.

+1


source







All Articles