compare two arrays Laravel

主宰稳场 提交于 2019-12-11 17:07:31

问题


I have articles that can contain different tags. For example, 5 pieces: (php, html, css, laravel, js) And I have groups that can also contain different tags. For example 4 pieces: (laravel, php, html, css)

I have already defined the relationships and it works. What I still lack is the linkage of article to the group.

In the Articlecontroller i use this so sync:

$article->groups()->sync($group->id);

Article Model

  public function groups()
  {
    return $this->belongsToMany('App\Group');
  }

    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable');
    }

Tag Model

public function articles()
{
    return $this->morphedByMany('App\Article', 'taggable');
}

public function groups()
{
    return $this->morphedByMany('App\Group', 'taggable');
}

Group Model

public function tags()
{
    return $this->morphToMany('App\Tag', 'taggable');
}

public function articles()
{
    return $this->belongsToMany('App\Article');
}

Controller

$groups = $user->groups()->latest()->with('tags')->paginate(20);
$mostvotedarticle = Article::where('type', 4)->whereIn('privacy', [1, 3])->orderByVotes()->first(); //show only article with the same tags
$imagearticle = Article::with('comments')->whereIn('type', [4, 5])->where('status', 1)->latest()->paginate(30); //show only articles with the same tags

I would now like to compare the tags of the groups and the tags of the posts. If the posts have the same tags as the group, I want to display the posts.


回答1:


simply check for equality

$equal = ($tagsFromPost == $tagsFromGroup) //TRUE if both have the same values but NOT in order
$equal = ($tagsFromPost === $tagsFromGroup) //TRUE if both have same values in SAME order

then something like

if($equal){
    <statements>
}

to check for FALSE if(!$equal)...



来源:https://stackoverflow.com/questions/52347942/compare-two-arrays-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!