基于具有不同元素的其他数组过滤php数组

时间:2018-02-04 19:15:28

标签: php arrays multidimensional-array

我有一个数组$items

[0] => Array (
  [itemid] => 8
  [name] => A
  [rating] => 9.5
)
[1] => Array (
  [itemid] => 41
  [name] => B
  [rating] => 9.5
)

和另一个数组$array如下:

[0] => Array (
  [itemid] => 458
  [name] => C
  [rating] => 9.603 
)
[1] => Array (
  [itemid] => 460
  [name] => D
  [rating] => 9.603
)
[2] => Array (
  [itemid] => 8
  [name] => A
  [rating] => 9.523
)
[3] => Array (
  [itemid] => 41
  [name] => B
  [rating] => 9.2
)

我想要做的是返回数组$array,但过滤掉$items中的所有元素。在这种情况下,它将返回$array,但没有[2]和[3]。

我尝试使用array_diff(),但评级可以从一个数组更改为另一个数组,因此一个数组中的元素并不总是与另一个数组中的元素相同。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

这是你正在寻找的吗?

<?php

$arr1 = [];
$arr1[] = [ "itemid" => 8, "name" => "A", "rating" => 9.5 ];
$arr1[] = [ "itemid" => 41, "name" => "B", "rating" => 9.5 ];

$arr2 = [];
$arr2[] = [ "itemid" => 458, "name" => "C", "rating" => 9.603 ];
$arr2[] = [ "itemid" => 460, "name" => "D", "rating" => 9.603 ];
$arr2[] = [ "itemid" => 8, "name" => "A", "rating" => 9.523 ];
$arr2[] = [ "itemid" => 41, "name" => "B", "rating" => 9.2 ];


function compare_by_itemid($a, $b) {
    return $a['itemid'] - $b['itemid'];
}

var_dump(array_udiff($arr2,$arr1,'compare_by_itemid'));

答案 1 :(得分:1)

您可以先将项ID值作为$ exclude关联数组(如集)的键,然后迭代$array以执行过滤:

$exclude = array_column($items, "itemid", "itemid"); // create set
foreach($array as $row) {
    if (!isset($exclude[$row["itemid"]])) $result[] = $row;
}

$result的条目ID不会出现在$items中。