将 Laravel 集合转换为数组,括号前后不带引号

Convert Laravel collection to Array without out quotes before and after brackets

如何删除数组左括号之前和右括号之后的引号。

private function get_sector_id ()
{
    $sectors = SectorUser::select('sector_id')->where('user_id', auth()->user()->id)->pluck('sector_id');

    dd(json_encode($sectors));
}

json_encode之前的输出:

Illuminate\Support\Collection {#310 ▼
  #items: array:2 [▼
    0 => "49ea267e-d11d-4fe9-ba62-c16d620688a3"
    1 => "6ba71f44-3c29-4fe3-b7ce-9d8a15e60f33"
  ]
}

尝试使用 json_encode 但 returns 在数组括号前后使用引号

"["49ea267e-d11d-4fe9-ba62-c16d620688a3","6ba71f44-3c29-4fe3-b7ce-9d8a15e60f33"]"

我想将输出转换为括号数组,以便我可以在查询中使用 whereNotIn,

目标是:

["49ea267e-d11d-4fe9-ba62-c16d620688a3","6ba71f44-3c29-4fe3-b7ce-9d8a15e60f33"]

以下代码 returns 一个集合,其元素为 sector_ids。

$sectors = SectorUser::select('sector_id')->where('user_id', auth()->user()->id)->pluck('sector_id');

幸运的是 Laravels whereNotIn 可以接受集合或数组。只需执行以下操作即可。可以看出here.

$sectorsWithoutSome = Sectors::whereNotIn($sectors)->get();

我认为,除了响应之外,将您的内部模型转换为 JSON 和 json_encode 是一种反模式。通常有更好的方法。

在您的 collection 上使用扁平化。

$sectors->flatten();

https://laravel.com/docs/7.x/collections#method-flatten