如果属性值在另一个数组中,php将从数组中删除[重复]

如果属性值在另一个数组中,php将从数组中删除[重复]

问题描述:

This question already has an answer here:

I want to remove all elements from arr2 that have a type contained in arr1:

    arr1 = ['A', 'B', 'C']

    arr2 = [
        [
        'name' => 'jane',
        'type' => 'X'
        ],
        [
        'name' => 'jon',
        'type' => 'B'
        ]
    ]

So jon should be removed. Is there some built in function like array_diff?

</div>

此问题已经存在 这里有一个答案: p>

  • 如何按值过滤二维数组 4 answers span> li> ul> div>

    我想删除arr2中包含类型的所有元素 在arr1: p>

      arr1 = ['A','B','C'] 
     
     
     arr2 = [
     [
    'name'=&gt;  'jane',
    'type'=&gt;  'X'
    ],
     [
    'name'=&gt;  'jon',
    'type'=&gt;  'B'
    ] 
    ] 
      code>  pre> 
     
     

    因此应删除jon。 是否有一些内置函数,如array_diff? p> div>

One of solutions using array_filter:

print_r(array_filter(
    $arr2, 
    function($v) use($arr1) { return !in_array($v['type'], $arr1); }
));

I don't think there's a way to do it with just one built-in array function, but you can combine some of them to do it.

$record_types = array_column($arr2, 'type');

$records_to_keep = array_diff($record_types, $arr1);

$result = array_intersect_key($arr2, $records_to_keep);

Foreach the 2nd array and check if the type is in arr1. If so then simply delete(unset) it.

foreach(array_keys(arr2) as $Key) {
   if (in_array(arr2[$Key]['type'],arr1)) { unset(arr2[$Key]); }
}

Here's another if the type is unique:

$result = array_diff_key(array_column($arr2, null, 'type'), array_flip($arr1));
  • extract an array from $arr2 keyed (indexed) by the type column
  • flip $arr1 to get values as keys
  • get the key differences

Run array_values on it to re-index if needed.