2016-11-22 58 views
3

是否有任何方法可以從多維集合中移除屬性?Laravel Collections - 除多維集合外使用

e.g我

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']);所以它爲每個?

回答

0

現在(Laravel 5.3)的確沒有比這個map(或transform)方法更簡單的方法。當你稍後再回到代碼中時,沒有什麼比較容易理解的。

雖然你可以擴展Collection,並在except中實現通配符,類似於pluck這樣做,但對我來說這是一個矯枉過正。