遍历数组的值相交

时间:2018-11-14 14:31:39

标签: php arrays laravel

我的数据库中有不同的社区,例如:community_newsfeed,community_marketplace,community_games_requested,community_games_offered,事件和custom_posts。 这些社区中的每个社区都存储一个post_id和user_id。 然后我有一个存储user_id和community_id的community_users表。

我想创建一种机制,我作为身份验证的用户,可以查看该用户的所有帖子,只要该用户和我属于同一社区即可。 在这方面,我必须仅查看我们都属于的社区的帖子。

所以我执行以下操作:

获取我(身份验证用户)所属的社区的所有社区ID:

You must specify a Parse class name when creating a new ParseObject.

然后,我对要查看帖子的用户执行相同操作:

$community_user_member = DB::table('community_users')->whereUserId($user->id)->pluck('community_id')->toArray();

好。现在,我使用数组交集给我所有我们仅共享的community_id:

$requested_user = DB::table('community_users')->whereUserId($user_id)->pluck('community_id')->toArray();

现在,这就是我被困住的地方。

如何获取ID匹配我在$ members值(不是键)中得到的值并且用户ID匹配$ user_id(在url中传递)的社区?

$members = array_intersect($community_user_member, $requested_user);

我确定该用户从community_newsfeed表中有4条帖子,但是我只看到2条帖子,而且我也没有看到正确的帖子。

实时示例:

用户A属于community_newsfeed。 用户B属于community_newsfeed和community_marketplace。

用户A必须看到community_newsfeed数据,其中user_id是用户B的ID。

已更新

我尝试的另一个选项是使用数组中的函数:

if(!empty($members)){
    $newsfeed = CommunityNewsfeed::whereIn('newsfeed_community_id', $members)->whereUserId($user_id)->get();
}

最终结果应该是这样的:

$common = [];
foreach ($community_user_member as $key => $member) {
    if (in_array($member, $requested_user)) {
        $common[] = $member;

    }
}
print_r($common);

因为这样我就可以遍历$ common数组并做我想做的事。

但是刷新页面时出现以下错误:

$common = [ '4','5','10','20' ];

0 个答案:

没有答案