猿问

Laravel 5.0 显示数组中的项,其中键的值与值匹配

我有一个看起来像这样的数组:


array:3 [▼

  0 => {#354 ▼

    +"id": 38

    +"block_newsletter_id": 102

    +"item_type": "title"

    +"html_key": ""

    +"content": "TITLE"

    +"properties": ""

  }

  1 => {#355 ▼

    +"id": 39

    +"block_newsletter_id": 102

    +"item_type": "text"

    +"html_key": ""

    +"content": "Some text. Hey."

    +"properties": ""

  }

  2 => {#356 ▼

    +"id": 40

    +"block_newsletter_id": 102

    +"item_type": "button"

    +"html_key": ""

    +"content": "click here"

    +"properties": ""

  }

]

现在我将此数组发送到我的视图,我的目标是在我的 h1 标签中显示 item_type“title”的内容。


我可以这样做:


@foreach($blockItemsContent as $blockItemContent)

    @if($blockItemContent->item_type == 'title')

        <h1>{{ $blockItemContent->content }}</h1>

    @endif

@endforeach

但是如果我想将 item_type 文本放在 ap 标签中,我也需要这样做。没有比必须为每个循环编写多个更有效的方法吗?


HUH函数
浏览 162回答 3
3回答

元芳怎么了

您可以在控制器中对每种类型进行分组,例如:collect($blockItemsContent)->groupBy('item_type');并将其传递给视图,您就有了自己的类型。

慕后森

您可以在控制器的方法中准备类似此数组的内容并将其发送到视图:$titleItemTypeContent = [];foreach ($blockItemsContent as $blockItemContent){&nbsp; &nbsp; if ($blockItemContent->item_type == 'title')&nbsp; &nbsp; &nbsp; &nbsp; $titleItemTypeContent[] = [$blockItemContent->id, $blockItemContent->content];}并$titleItemTypeContent根据需要在刀片中重复使用多次。

子衿沉夜

根据您的问题 If item_type = title 则显示在 h1 标签中 If item_type = text 然后显示在 p 标签中其他显示在span标签中在刀片文件中:@foreach($blockItemsContent as $item)&nbsp; &nbsp; &nbsp;@if($item->item_type == 'title')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<h1>{{ $item->content }}</h1>&nbsp; &nbsp; &nbsp;@elseif($item->item_type == 'text')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<p>{{ $item->content }}</p>&nbsp; &nbsp; &nbsp;@else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>{{$item->content}}</span>&nbsp; &nbsp; &nbsp;@endif@endforeach
随时随地看视频慕课网APP
我要回答