Laravel 5.2刀片 - 未定义的偏移量:在我的循环中为5

时间:2017-01-04 14:53:15

标签: php laravel blade

我正在创建我的文章的管理员,在我的资源编辑帖子中我有一些问题,我想显示我的帖子的所有标签,我正在编辑,我尝试这样:

我创建了一个变量数组,其中所有标签都与编辑后的id关系:

 $post_tags[0]->tag_id // it return some id of tag's post

现在我将在我的表单edit.blade.php中显示所有标记的帖子,例如输入

    @for ($i = 0; $i < count($all_tags); $i++)

        @if($all_tags[$i]->id != $post_tags[$i]->tag_id)
           <input style="cursor: pointer;" type="checkbox" name="tags[]" id=" {{$all_tags[$i]->slug}}" value="{{$all_tags[$i]->id}}" data-parsley-mincheck="2"  class="flat"/>
        @else
           <input style="cursor: pointer;" type="checkbox" name="tags[]" id="{{$all_tags[$i]->slug}}" value="{{$all_tags[$i]->id}}" data-parsley-mincheck="2"  class="flat" checked/> 
    @endif

 @endfor
  

但我收到此错误:

     

Collection.php第1187行中的ErrorException:未定义的偏移量:5(查看:   C:\ XAMPP \ htdocs中\ sofis \资源\视图\管理员\交\ edit.blade.php)

4 个答案:

答案 0 :(得分:3)

幼虫5.3及以上

正如其他人所说,你需要检查以确保索引存在。您还可以使用@foreach代替@for来简化逻辑:

@foreach ($all_tags as $tag)
    <input style="cursor: pointer;" type="checkbox" name="tags[]" id=" {{$tag->slug}}" value="{{$tag->id}}" data-parsley-mincheck="2"  class="flat" {{ (isset($post_tags[$loop->index]) && $post_tags[$loop->index]->tag_id == $tag->id) ? 'checked' : '' }} />
@endforeach

答案 1 :(得分:1)

这意味着$post_tags[$i]没有索引= 5的元素。如果您不确定此索引的元素是否存在,则不应使用$array[$index]方法。或者你应该在使用前检查它:

@if (isset($post_tags[$i]) && $all_tags[$i]->id != $post_tags[$i]->tag_id)

答案 2 :(得分:1)

您可以改进Samsquanch的答案以匹配小于5.3的版本。您可以通过在$key中定义foreach()来访问数组索引,如下图所示。

@foreach ($all_tags as $key => $tag)
    <input style="cursor: pointer;" type="checkbox" name="tags[]" id=" {{$tag->slug}}" value="{{$tag->id}}" data-parsley-mincheck="2"  class="flat" {{ (isset($post_tags[$key]) && $post_tags[$key]->tag_id == $tag->id) ? 'checked' : '' }} />
@endforeach

答案 3 :(得分:0)

我猜$post_tags没有索引5,因此$post_tags[$i]失败