Blade 模板 - 使用 foreach 根据值将数组拆分为两个数组
Blade template - use foreach to split array into two array based on value
我是一个完全 Laravel Blade 菜鸟,正在尝试做一些我知道如何在 JavaScript 中做但需要在 Blade 模板中做的事情。
我想遍历下面这个对象 $site->links()->orderBy('position')->get()并评估每个 $link->type 并根据值推送到两个新数组之一。所以...
global $navlinks = [];
global $legallinks = [];
// main loop
@foreach($site->links()->orderBy('position')->get() as $link)
// blavascript concept of what I need.
@if($link->type == 'nav') $navlinks.push($link)
@if($link->type == 'legal) $legallinks.push($link)
...
// Do something with new $navlinks and $legallinks arrays
我希望这是有道理的...
嗯,这对我来说看起来很“合乎逻辑”,所以我认为它应该在其他地方完成,但在 blade 中你可以这样做:
@php
$navlinks = [];
$legallinks = [];
@endphp
// main loop
@foreach($site->links()->orderBy('position')->get() as $link)
@if($link->type == 'nav') @php $navlinks[] = $link; @endphp
@if($link->type == 'legal) @php $legallinks[] = $link; @endphp
@endforeach
或者,因为 ->get()
将 return 一个 Collection
:
@php
$res = $site->links()
->orderBy('position')
->get()
->reduce(function($acc, $val){
$acc[$link->type][] = $val;
return $acc;
}, [
'nav' => [],
'legal' => []
])
@endphp
@foreach($res['legal'] as $legal) ... @endforeach
@foreach($res['nav'] as $nav) ... @endforeach
我是一个完全 Laravel Blade 菜鸟,正在尝试做一些我知道如何在 JavaScript 中做但需要在 Blade 模板中做的事情。
我想遍历下面这个对象 $site->links()->orderBy('position')->get()并评估每个 $link->type 并根据值推送到两个新数组之一。所以...
global $navlinks = [];
global $legallinks = [];
// main loop
@foreach($site->links()->orderBy('position')->get() as $link)
// blavascript concept of what I need.
@if($link->type == 'nav') $navlinks.push($link)
@if($link->type == 'legal) $legallinks.push($link)
...
// Do something with new $navlinks and $legallinks arrays
我希望这是有道理的...
嗯,这对我来说看起来很“合乎逻辑”,所以我认为它应该在其他地方完成,但在 blade 中你可以这样做:
@php
$navlinks = [];
$legallinks = [];
@endphp
// main loop
@foreach($site->links()->orderBy('position')->get() as $link)
@if($link->type == 'nav') @php $navlinks[] = $link; @endphp
@if($link->type == 'legal) @php $legallinks[] = $link; @endphp
@endforeach
或者,因为 ->get()
将 return 一个 Collection
:
@php
$res = $site->links()
->orderBy('position')
->get()
->reduce(function($acc, $val){
$acc[$link->type][] = $val;
return $acc;
}, [
'nav' => [],
'legal' => []
])
@endphp
@foreach($res['legal'] as $legal) ... @endforeach
@foreach($res['nav'] as $nav) ... @endforeach