【问题标题】:Laravel Collections - Using Except on multidimensional collectionLaravel 集合 - 在多维集合上使用 except
【发布时间】:2017-04-06 03:02:26
【问题描述】:

有没有什么方法可以从多维集合中移除属性?

例如我有

public function getPossibleAnswersAttribute()
{
    return collect([
        [
            'option' => 'A',
            'answer' => $this->answer_1,
            'points' => $this->answer_1_value
        ],
        [
            'option' => 'B',
            'answer' => $this->answer_2,
            'points' => $this->answer_2_value
        ],
        [
            'option' => 'C',
            'answer' => $this->answer_3,
            'points' => $this->answer_3_value
        ],
        [
            'option' => 'D',
            'answer' => $this->answer_4,
            'points' => $this->answer_4_value
        ]
    ]);
}

public function getPossibleAnswersWithoutPointsAttribute()
{
    $answers = $this->getPossibleAnswersAttribute()
    ->except(['0.points']);
    return $answers;
}

我正在尝试获取相同的集合,但没有积分键/属性。

我知道我可以这样做

->map(function ($item) {
    unset($item['points']);
    return $item;
});

但是我希望有一种更流畅的方式来做到这一点,因为我发现我可以做到 ->except(['0.points']); 将它从第一个删除,我在想是否有一个神奇的关键字,它算作一个关键?类似于->except(['#.points']);,所以它对每个人都这样做?

【问题讨论】:

    标签: php laravel multidimensional-array collections except


    【解决方案1】:

    目前(Laravel 5.3)真的没有比map(或transform)方法更简单的了。当您稍后回到代码时,肯定没有什么比这更容易理解的了。

    您可以扩展 Collection,并在 except 中实现通配符,类似于 pluck 的做法,但对我来说,这有点过头了。

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 2019-07-05
      • 2020-12-29
      • 2019-11-17
      • 2019-03-30
      • 2018-07-19
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多