我有一个名为
$roster
的数组,其中大约有 16 个较小的数组,如下所示(为简洁起见,仅显示 4 个):
Array
(
[0] => Array
(
[playerid] => 1055
[firstname] => Christian
[lastname] => McCaffrey
[age] => 27
)
[1] => Array
(
[playerid] => 1362
[firstname] => A.J.
[lastname] => Brown
[age] => 26
)
[2] => Array
(
[playerid] => 1897
[firstname] => Joe
[lastname] => Burrow
[age] => 27
)
[3] => Array
(
[playerid] => 2019
[firstname] => De'Von
[lastname] => Achane
[age] => 22
)
)
我还有一个名为
$notneeded
的单独数组,其中仅包含playerid,如下所示:
Array
(
[0] => 1055
[1] => 1495
[2] => 1497
[3] => 1897
[4] => 1775
)
我想循环遍历上面的数组,如果这 5 个玩家 ID 中的任何一个与较大数组中的玩家 ID 匹配,我想删除整个记录。
例如,由于 1055 和 1897 位于上面较小的数组中,我希望生成的数组中只剩下 2 个玩家(因为应删除 McCaffrey 和 Burrow 的所有信息)。
我尝试了下面的代码,但没有发生任何事情(即没有任何内容从
$roster
中删除)
foreach ($notneeded as $item) {
// Search values and remove them from $roster
if(($key = array_search($item, $roster)) !== false) {
unset($roster[$key]);
}
}
显然我不擅长数组,因为这看起来应该有点简单。请让我知道我做错了什么/愚蠢的:)
array_filter
函数。
来自文档:
array_filter(array $array, ?callable $callback = null, int $mode = 0):
迭代数组中的每个值,并将它们传递给回调函数。如果回调函数返回 true,则数组中的当前值将返回到结果数组中。
根据您的情况,您可以使用:
$roster = array_filter($roster, function($element) use ($notneeded) {
return in_array($element, $notneeded);
});