根据条件过滤对象数组

时间:2021-06-14 20:15:02

I have an array in the following format :-

我有一个以下格式的数组: -

[
 { name : "Foo",
   type : "Bar"
 },
 { 
  name : "Foo",
  type : "Row"
 },
 { 
  name : "Foo"
 }
]

I would like to remove occurrences of "Foo" only when it doesn't have a type. Basically, there can be duplicates in the array as long as the type is different and there can not be a duplicate with no type. Any help is appreciated!

我想仅在没有类型的情况下删除“Foo”的出现。基本上,只要类型不同并且不存在没有类型的重复,数组中就可能存在重复项。任何帮助表示赞赏!

Thanks!

1 个解决方案

#1


2  

I am assuming that you are working with a json_decoded array of objects. IN that case, you could run a simple array_filter() like this:

我假设您正在使用json_decoded对象数组。在这种情况下,您可以像这样运行一个简单的array_filter():

$filtered_array = array_filter($array, function($item) {
   return isset($item->type);
});

#1


2  

I am assuming that you are working with a json_decoded array of objects. IN that case, you could run a simple array_filter() like this:

我假设您正在使用json_decoded对象数组。在这种情况下,您可以像这样运行一个简单的array_filter():

$filtered_array = array_filter($array, function($item) {
   return isset($item->type);
});