1 回答
TA贡献1831条经验 获得超10个赞
<?php
$user1->user_id = 2;
$user1->full_name = 'User B';
$user1->image = '1582735876user-a.png';
$user2->user_id = 3;
$user2->full_name = 'User C';
$user2->image = '1582735876user-a.png';
$user3->user_id = 4;
$user3->full_name = 'User D';
$user3->image = '1582735876user-a.png';
$user4->user_id = 3;
$user4->full_name = 'User C';
$user4->image = '1582735876user-a.png';
$users = [$user1, $user2, $user3];
$blackListedUsers = [$user4];
$res = array_filter($users, function ($user) use ($blackListedUsers) {
return !in_array($user, $blackListedUsers);
});
var_dump($res);
将array_filter与匿名函数一起使用;和in_array。阅读in_array
文档以查看它是否符合您的需要,因为它正在比较两个对象,您可以使用一个自定义函数,该函数仅在两个对象的 ID 相等时进行测试。
更新
或者更适合初学者的代码版本:
<?php
$user1->user_id = 2;
$user1->full_name = 'User B';
$user1->image = '1582735876user-a.png';
$user2->user_id = 3;
$user2->full_name = 'User C';
$user2->image = '1582735876user-a.png';
$user3->user_id = 4;
$user3->full_name = 'User D';
$user3->image = '1582735876user-a.png';
$user4->user_id = 3;
$user4->full_name = 'User C';
$user4->image = '1582735876user-a.png';
$users = [$user1, $user2, $user3];
$blackListedUsers = [$user4];
$validUsers = [];
foreach ($users as $user) {
if (!isBlacklisted($user, $blackListedUsers)) {
$validUsers[] = $user;
}
}
var_dump($validUsers);
function isBlacklisted($user, $blackListedUsers) {
foreach ($blackListedUsers as $blackListedUser) {
if ($user->user_id == $blackListedUser->user_id) {
return true;
}
}
return false;
}
- 1 回答
- 0 关注
- 123 浏览
添加回答
举报