dongtaijiao7140 2018-08-15 09:45
浏览 96
已采纳

Laravel使用数组并通过关联数组进行循环

Consider I have the following array (passed to view from my controller):

'first' => [

    '1' => [
        'title' => 'First Div',
        'fields' => [
            'name', 'select'
        ],
    ],

     'divider',

    '2' => [
        'title' => 'Second Div',
        'fields' => [
            'address'
        ],
    ],

Looks like this in the browser when I dump:

array (size=2)
  1 => 
    array (size=2)
      'title' => string 'First Div' (length=9)
      'fields' => 
        array (size=2)
          0 => string 'name' (length=4)
          1 => string 'select' (length=6)
  2 => 
    array (size=2)
      'title' => string 'Second Div' (length=10)
      'fields' => 
        array (size=1)
          0 => string 'address' (length=7)

What I am trying to do is the following. I want to loop through all arrays, then display a div with a title, and within that div, loop through all the fields for each array.

For now I am focussing on just the looping through the array and displaying the right data, so without any divs yet. So something like this:

@foreach($first as $key => $value)

    // Unsure what to do here

@endforeach

I've tried a lot of things (just playing around trying to dump or echo out data), and I cannot even figure out how to display the title, let alone loop through all the fields values.

Either way, my ultimate goal is to create the following, dynamic view, based on what is passed from the controller:

Example

  • 写回答

1条回答 默认 最新

  • dtj4307 2018-08-15 09:50
    关注

    To echo out a value in blade you can wrap your variable in {{ }}.

    You should be able to do something along the lines of:

    @foreach($first as $key => $value)
    
        <div>
            <h2>{{ $value['title'] }}</h2>
    
            @foreach($value['fields'] as $field)
    
                {{ $field }} <br>
    
            @endforeach
        </div>
    
    @endforeach
    

    Please view the documentation for more information

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看