简体   繁体   English

从PHP数组中删除类似的元素

[英]Removing similar elements from a 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 the similar elements where the fist and last name are the same. 我需要删除拳头和姓氏相同的类似元素 Normally, I would use array_unique but the elements aren't exactly unique since each one has a unique id. 通常,我会使用array_unique,但元素并不完全唯一,因为每个元素都有唯一的id。 I do not care which id is retained. 我不关心保留哪个ID。 I just need the 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 accomplish this? 有没有快速的方法来实现这一目标? My first thought is to use something like a bubble sort but I'm wondering if there is a better (faster) way. 我的第一个想法是使用像冒泡一样的东西,但我想知道是否有更好(更快)的方式。 The resulting array is being added to a drop-down list box and the duplicate entries is confusing some users. 生成的数组将添加到下拉列表框中,并且重复的条目会使某些用户感到困惑。 I'm using the ID to pull the record back from the DB after it is selected. 选中后,我正在使用ID从DB中取回记录。 Therefore, it must be included in the array. 因此,它必须包含在数组中。

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

This definitely works , whether it is the best way is up for debate... 这绝对有效 ,无论是辩论的最佳方式......

Codepad 键盘

There is no fast and easy way that I know of, but here is a relatively simple way of doing it assuming that the ids for "similar elements" don't matter (ie you just need an ID period). 我知道没有快速简便的方法,但这是一种相对简单的方法,假设“类似元素”的ID无关紧要(即你只需要一个ID周期)。

$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 the derived keys. 最后一步并非严格必要..仅当您要删除派生密钥时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM