laravel-集合忘记子集合

时间:2018-08-23 08:07:50

标签: php laravel

我有多维收藏集,例如

Collection {#968 ▼
  #items: array:7 [▼
    "Root Lorem Ipsum #1" => Collection {#980 ▼
      #items: array:3 [▼
        0 => {#970 ▼
          +"id": "5048"
          +"name": "lorem Ipsum"
          +"slug": "lorem-ipsum"
        }
        1 => {#972 ▶}
        2 => {#974 ▶}
      ]
    }
    "Root Lorem Ipsum #2" => Collection {#982 ▶}
  ]
}

现在,我有用于“删除”重复项的过滤器:

    $categories = $categories->map(function ($chapter) {
        return $chapter->map(function ($category) use ($chapter) {
            if ($chapter->where('name', $category->name)->count() === 2) {
                $tmp = $chapter
                    ->where('name', $category->name)
                    ->where('id', '!=', $category->id)
                    ->first()
                ;

                $category->id = $category->id. ',' .$tmp->id;
                $chapter->forget($tmp);
            }

            return $category;
        });
    });

$chapter->forget($tmp);上,我想将其从收藏夹中删除,但似乎无法正常工作。我该怎么办?

2 个答案:

答案 0 :(得分:0)

forget方法通过键将其从集合中删除: https://laravel.com/docs/5.6/collections#method-forget

由于我们正在价值部分尝试它,因此无法正常工作。

使用唯一方法来过滤唯一记录 https://laravel.com/docs/5.6/collections#method-unique

 $categories = $categories->map(function ($chapter) {
    return $chapter->map(function ($category) use ($chapter) {
       return $category->unique('name');
    });
});

答案 1 :(得分:0)

使用链接,如下所示:

$chapter->map(function ($category) use (**&**$chapter) {}