【问题标题】:How to create nested collections in Laravel?如何在 Laravel 中创建嵌套集合?
【发布时间】:2016-07-28 14:56:59
【问题描述】:

我正在尝试在 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 ▶}
    ]
  ]
]

【问题讨论】:

  • 您可以通过 collect() 传递现有数组并在其上执行 Collection 方法。或者您可以简单地使用 put() 和 push() 组装数组。 laravel.com/docs/5.2/collections#method-put
  • 你没有很好地表达你的目标。如果您只想使用当前数组结构创建集合,只需简单的 collect($groups) ,.

标签: php arrays laravel


【解决方案1】:

您可以为此使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2022-01-07
    • 2020-02-21
    • 2021-03-02
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多