【问题标题】:php - get rid of duplicate items from array of objects in php [duplicate]php - 从 php 中的对象数组中删除重复项
【发布时间】:2018-07-22 22:53:10
【问题描述】:

如何删除 php 关联数组中的重复项?该数组是从 JSON 创建的。

    array (size=646)
  0 => 
    object(stdClass)[1]
      public 'id' => string '1' (length=1)
      public 'name' => string 'John' (length=4)
      public 'city' => string 'NY' (length=2)

  1 => 
    object(stdClass)[3]
      public 'id' => string '2' (length=1)
      public 'name' => string 'Henry' (length=5)
      public 'city' => string 'Mexico' (length=6)
  2 => 
    object(stdClass)[5]
      public 'id' => string '2' (length=1)
      public 'name' => string 'Jordan' (length=6)
      public 'city' => string 'Lake' (length=4)
              ...

我尝试使用array_unique($data),但我仍然得到重复的值。我只想通过id 获得那些独特的元素。 TIA。

【问题讨论】:

  • 您是否认为重复值是具有相同id 属性的对象?具有id = 2 的两个给定对象中哪一个具有更高的优先级?
  • 是的,我将在表格中显示它。
  • 第二个还是第一个都没有关系。
  • 您可以通过 id 重新索引数组:$unique = array_column($array, null, 'id');(需要 PHP 7)
  • @Barmar 公平地说,您所指出的问题中的所有答案都非常垃圾......

标签: php arrays


【解决方案1】:

一种可能的解决方案:

$arr = array_values(array_reduce($arr, function($arr, $x) {
    $arr[$x->id] = $x;
    return $arr;
}, []));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-24
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多