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 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)