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

时间:2017-10-19 01:21:46

标签: mysql arrays laravel blade

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

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"
            ]
          ]
        }   ] }

STYLISH HAT

颜色:绿色,蓝色,红色

销售日期:2017-10-16

CLASSIC HAT

颜色:黑色

销售日期: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

2 个答案:

答案 0 :(得分:0)

使用集合类中的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

答案 1 :(得分:0)

如果其他人在Laravel中使用groupBy在嵌套数组的输出上苦苦挣扎,我发现这样做最干净的方法如下。主循环是groupBy字段,内循环是每个组的不同特征。我的收藏也与上面的例子略有不同。

我构建了我的数组,首先抓取所有记录,然后按照我想要的字段进行分组。

      $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

不确定这是否过于抽象,无法帮助其他任何人,也许这不是最好的方式,但是我花了一点时间狩猎并拼凑了我读过的不同内容来理解这一点。