沃梦达 / 编程问答 / php问题 / 正文

Laravel Eloquent Pluck 不会丢失钥匙

Laravel Eloquent Pluck without losing the key(Laravel Eloquent Pluck 不会丢失钥匙)

本文介绍了Laravel Eloquent Pluck 不会丢失钥匙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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']];
});

这篇关于Laravel Eloquent Pluck 不会丢失钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel Eloquent Pluck 不会丢失钥匙

基础教程推荐