我试图在Laravel中创建一个嵌套集合。目前我正在使用多维数组:
foreach ($combination->attributes as $attr) {
$groups['group'][$attr->group->language->name][] = $attr->language;
}
我如何使用Laravel集合复制它?我希望能够利用lists方法和groupBy方法吗?
这是数据的样子:
array:1 [▼
"group" => array:2 [▼
"Finish" => array:3 [▼
0 => AttributeLanguage {#257 ▶}
1 => AttributeLanguage {#234 ▶}
2 => AttributeLanguage {#256 ▶}
]
"Print Size" => array:3 [▼
0 => AttributeLanguage {#252 ▶}
1 => AttributeLanguage {#252 ▶}
2 => AttributeLanguage {#252 ▶}
]
]
]
答案 0 :(得分:0)
您可以将groupBy()
用于此
例如:
$collection = collect([
['language' => 'hindi', 'product' => 'Chair'],
['language' => 'hindi', 'product' => 'Bookcase'],
['language' => 'english', 'product' => 'Desk'],
]); // this is for showing array may be like
OR
$collection = AttributeLanguage::all(); // this might you are using or any other way.
$grouped = $collection->groupBy('language'); // this is a collection you can see by using dd($grouped) here.
在此处将集合显示为数组。
$grouped->toArray();
/*
[
'hindi' => [
['language' => 'hindi', 'product' => 'Chair'],
['language' => 'hindi', 'product' => 'Bookcase'],
],
'english' => [
['language' => 'english', 'product' => 'Desk'],
],
]
*/
更多访问Laravel文档:https://laravel.com/docs/5.2/collections#method-groupby