我也很想知道它們都是什麼名字?例如一個數組項引用像$ item ['名稱']和$ item->名稱,如果有一個術語給他們! (不是關鍵,值)
$items = collection([
[
'name' => 'test item 1',
'description' => 'this is a description',
],
[
'name' => 'test item 1',
'description' => 'this is a description',
],
[
'name' => 'test item 1',
'description' => 'this is a description',
],
]);
然後在刀片或任何ID愛能夠引用他們像
foreach($items as $item) {
echo $item->name;
}
,而不是
foreach($items as $item) {
echo $item['name'];
}
編輯
解決謝謝你們的答案。
$collection->map(function ($section) {
return (object) [
'label' => $section['label'],
'items' => collect($section['items'])->map(function ($item) {
return (object) $item;
}),
];
});
下面的完整代碼還用於檢查集合中是否存在項目。
protected $collection = [];
public function __construct()
{
parent::__construct();
$this->collection = collect([
[
'label' => 'Section label 1',
'items' => [
[
'label' => 'Item label 1',
'description' => 'Item description',
],
],
],
[
'label' => 'Section label 2',
'items' => [
[
'label' => 'Item label 2',
'description' => 'Item description',
],
],
],
[
'label' => 'Section label 3',
'items' => [
[
'label' => 'Item label 3',
'description' => 'Item description',
],
],
],
])
->map(function ($section) {
return (object) [
'label' => $section['label'],
'items' => collect($section['items'])->map(function ($item) {
return (object) $item;
}),
];
});
}
public function show($slug = '')
{
$item = $this->getItem($slug);
if (null === $item) {
abort(404);
}
return view('show')
->withItem($item);
}
protected function getItem($slug)
{
return $this
->collection
->flatMap(function ($section) {
return $section->items;
})
->first(function ($item) use ($slug) {
return str_slug($item->label) === $slug;
});
}
所以你需要創建'object',而不是'array'。 – JYoThI
瑞科利克打敗了我。要完成你的問題,在這裏命名'$ item-> name'是對象的一個屬性。此外,作爲一個函數收集不存在,它只需要'collect()' – mbozwood
這是要麼收集(['數組項'去']或'新照明\支持\收藏(['數組項' ])'not'collection()' –