比较arays并排除元素形式之一(如果元素形式重复)

时间:2019-06-25 14:37:35

标签: php arrays laravel

我需要比较数组,如果第一个或第二个数组中的元素在另一个数组中有重复,则需要排除它。我知道这听起来很简单,但我敢肯定,但是我无法解决这个问题:(

所以我有第一个像这样的数组:

Array:3 [
    6 => blog/something
    4 => blog/somethingElse
    5 => blog/else
]

第二个数组几乎相同:

Array:3 [
    1 => /blog
    2 => /comments
    3 => /posts
]

最后一个数组:

(integer on the left is id of elements in second array, in this example 
comments and posts)
Array:2 [
    0 => array:2 [
        'page_id' => 2
         'value'  => noindex 
    ]
    1 => array:2 [
         'page_id' => 3
         'value'  => noindex 
 ]
 ]

因此,如果我在数组的第一个或第二个元素中也存在于数组thrid中,并且值= noindex,则需要排除它。

我曾尝试通过foreach递归,array_walk_recursive来做到这一点,但我仍然无法获得满意的结果

2 个答案:

答案 0 :(得分:1)

首先获取您需要排除的所有索引,然后排除它们:

$excludeIndices = array_column(array_filter($array3, function ($entry) {
   return $entry['value'] === 'noindex';
}), 'page_id');

$keepArray1 = array_diff_key($array1, array_flip($excludeIndices));
$keepArray2 = array_diff_key($array2, array_flip($excludeIndices));

Sandbox

答案 1 :(得分:0)

您可以直接使用前两个数组进行过滤。

$result = array_filter($last, function($item) use ($first, $second) {
    return !($item['value'] == 'noindex' &&
            (isset($first[$item['page_id']]) || isset($second[$item['page_id']]))
    );
});