如何在 Laravel 中循环并输出嵌套数组

How to loop through and output nested array in Laravel

在这个示例中,我试图遍历嵌套数组并输出以下信息。

Collection {#252 ▼   #items: array:1 [▼
        0 => Collection {#258 ▼
          #items: array:4 [▼
            0 => array:3 [▼
              0 => "Stylish Hat"
              1 => "Green"
              2 => "2017-10-16 17:57:49"
            ]
            1 => array:3 [▼
              0 => "Stylish Hat"
              1 => "Blue"
              2 => "2017-10-16 17:57:49"
            ]
            2 => array:3 [▼
              0 => "Stylish Hat"
              1 => "Red"
              2 => "2017-10-16 18:00:24"
            ]
            3 => array:3 [▼
              0 => "Classic Hat"
              1 => "Black"
              2 => "2018-10-16 18:00:24"
            ]
          ]
        }   ] }

时尚帽子

颜色:绿色、蓝色、红色

发售日期:2017-10-16


经典帽子

颜色:黑色

发售日期:2018-10-16


我尝试了各种方法都没有成功输出,所以我不确定我当前的代码是否有任何价值,但这是我在黑暗中的尝试,当然是完全错误的...

@foreach ($hatData->toArray() as $hatStyle => $color => $saleDate)
         <div style="color:#333;font-size:14pt;">
            <b>{{ $hatStyle }}</b>
         </div>
         @foreach($colors as $color)
            <div style="color:#333;font-size:10pt;">
               colors: {{ $color }}
            </div>
            <div>
               Sale Date: {{ $saleDate }}
            </div>
         @endforeach
      @endforeach

像这样使用集合 class 中的 groupBy:

$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);

$grouped = $collection->groupBy('account_id');

$grouped->toArray();

/*
    [
        'account-x10' => [
            ['account_id' => 'account-x10', 'product' => 'Chair'],
            ['account_id' => 'account-x10', 'product' => 'Bookcase'],
        ],
        'account-x11' => [
            ['account_id' => 'account-x11', 'product' => 'Desk'],
        ],
    ]
*/

https://laravel.com/docs/5.5/collections#method-groupby

如果其他人正在努力处理 Laravel 中带有 groupBy 的嵌套数组的输出,我发现最简洁的方法如下。主循环是 groupBy 字段,内循环是每个组的不同特征。我的 collection 的构造也与上面的示例略有不同。

我通过首先抓取所有记录然后按我想要的字段分组来构建我的数组。

      $mainCollection=records::where('this','=','that')->get();      

      $selected = $mainCollection->map(function ($item) {
          return [
            'mainValue'=>$item->mainValue,
            'itemOne' => $item->itemOne,
            'itemTwo' => $item->itemTwo
          ];
      });

      $mainLoop=$selected->groupBy('mainValue');

然后输出我使用了下面的循环

      @foreach ( $mainLoop as $ml )

         <div>
            <u>{{ $ml[0]['mainValue'] }}</u>
         </div>

         @foreach( $ml as $item)
            <div>
               {{$item['itemOne']}} - {{ $item['itemTwo'] }}
            </div>
         @endforeach

      @endforeach

不确定这是否太抽象而无法帮助其他人,也许这不是最好的方法,但我花了一点时间寻找和拼凑我阅读的不同内容以理解这一点。