I have an array $items
as such:
[0] => Array (
[itemid] => 8
[name] => A
[rating] => 9.5
)
[1] => Array (
[itemid] => 41
[name] => B
[rating] => 9.5
)
and another array $array
as such:
[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
)
What I would like to do is return the array $array
, but with all the elements from $items
filtered out. In this case it would return $array
, but without [2] and [3].
I've tried with array_diff()
, but the rating can change from one array to the other, so the elements in the one array are not always the same as in the other array.
How do I go about this?
Is this what you're looking for?
<?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'));
You could first get the item ID values as keys of an $exclude associative array (like a set), and then iterate $array
to perform the filter:
$exclude = array_column($items, "itemid", "itemid"); // create set
foreach($array as $row) {
if (!isset($exclude[$row["itemid"]])) $result[] = $row;
}
The $result
will have entries with item IDs that do not occur in $items
.