首页 > 解决方案 > 如何在 for 和 if 语句中使用动态数组索引,因为我在 laravel Blade 中得到了 Undefined offset: 1

问题描述

我是 laravel 的新手,当我想使用变量访问数组时,我遇到了 Undefined offset: 1 错误。

如何在 for 和 if 语句中使用索引?

这是我的代码。

@for($i = 0; $i< count($type['layout']); $i++)
   @if($type['layout']['col'] == 1)
      @if($type['layout']['properties'][$i]['type'] == "text")
         text input
      @else if($type['layout']['properties'][0]['type'] == "radio")
         radio btn
      @endif
   @endif
@endfor

数组格式在这里

array:1 [▼
   "layout" => array:2 [▼
   "col" => "1"
   "properties" => array:1 [▼
        0 => array:3 [▼
           "type" => "text"
           "label" => "username"
           "text" => "Enter your username"
         ]
      ]
   ]
]

这是错误的图像

标签: laravel

解决方案


你错过了循环键。更改为:

$type['layout'][$i]['col'] == 1

您错过了这一行中的循环键:@if($type['layout']['col'] == 1)

在此处输入图像描述


推荐阅读