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

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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀