简体   繁体   English

通过比较项目节点唯一的数组

[英]Array unique by comparing a node of an item

I want to remove duplicated objects of an array of objects. 我想删除对象数组中的重复对象。 For example, I got an array like this one : 例如,我得到了一个像这样的数组:

array
  0 => 
    object(stdClass)
      public 'object_id' => string '13' (length=2)
      public 'object_data' => float 5
  1 => 
    object(stdClass)
      public 'object_id' => string '13' (length=2)
      public 'object_data' => float 5
      public 'random_data' => float 15
  2 => 
    object(stdClass)
      public 'object_id' => string '14' (length=2)
      public 'object_data' => float 25
      public 'random_data' => float 35

I was using the function 我正在使用该功能

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

to remove the duplicated objects but those I have above are not identical, so I was wondering if it is possible to remove those duplicated according to an specific node " object_id " instead of comparing the full object? 删除重复的对象,但上面的对象并不相同,所以我想知道是否有可能根据特定节点“ object_id ”删除重复的对象,而不是比较整个对象?

Is that posible ? 那可以吗?

Also in the case of getting 2 similar objects like above, can I keep the one with the " random_data " on it ? 同样在获得2个类似上面的对象的情况下,我可以保留上面带有“ random_data ”的对象吗?

Should I use a loop and traverse all the objects or is there any way to do it with a function like *array_unique*? 我应该使用循环遍历所有对象,还是可以通过* array_unique *之类的函数来完成此操作?

Thank you 谢谢

You can try with: 您可以尝试:

$input  = array( /* your array of objects */ );
$output = array();

foreach ( $input as $obj ) {
  $id = $obj->object_id;
  if ( !isset($output[$id]) ) {
    $output[$id] = array();
  }

  $output[$id] = (object) array_merge((array) $output[$id], (array) $obj);
}

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

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