Laravel Eloquent Pluck 不会丢失钥匙

2021-12-26 00:00:00 php laravel eloquent

我在 Laravel 中有以下集合:

I have the following collection in Laravel:

 ["TheNumbers":[{"episodeID":16818,"episodeNumber":100,"created_at":null,"updated_at":null},{"episodeID":16818,"episodeNumber":210,"created_at":"2017-02-20 21:30:38","updated_at":"2017-02-20 21:30:38"}]

如果我运行以下代码:

$TheEpisode->TheNumbers->pluck('episodeNumber');

我会得到以下结果:

[100,210]

我想保留每个号码的密钥,我该如何实现?

I would like to keep the keys for each number, how can I achieve this?

这是我的预期结果:

[{"episodeNumber":100},{"episodeNumber":210}]

PHILIS PETERS(改进)

TheEpisode->TheNumbers->reduce(function ($result, $episode) {
          $episodeData = (collect())->put('episodeNumber', $episode['episodeNumber']);
          $result[] = $episodeData;
          return $result;
        }));

推荐答案

尝试这样的事情,它应该可以使用 map...

Try something like this, it should work using map...

return $TheEpisode->TheNumbers->map(function ($episode) {
    return ['episodeNumber' => $episode['episodeNumber']];
});

相关文章