【发布时间】:2018-01-18 08:59:33
【问题描述】:
我也想知道他们俩叫什么名字?例如一个像 $item['name'] 和 $item->name 引用的数组项,如果它们有一个术语的话! (不是键,值)
$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',
],
]);
然后在刀片或任何我喜欢能够引用它们的地方
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。 -
Regolith 打败了我。要完成您的问题,请在此处命名
$item->name是对象的属性。另外,集合作为函数不存在,它只需要collect() -
是
collect(['array items go here']或new Illuminate\Support\Collection(['array items'])不是collection()
标签: php arrays laravel collections