猿问

在 Laravel 中,我很难理解使用 @foreach 遍历刀片中的数组所需的语法

我在读取从控制器传递到刀片的以下“$photos”数组时遇到问题。


  0 => array:2 [▼

    "destinationPath" => "images/"

    "filename" => "15-1-tue-apr-7-2020-130-am-34824.jpg"

  ]

  1 => array:1 [▼

    0 => array:2 [▼

      "destinationPath" => "images/"

      "filename" => "15-1-tue-apr-7-2020-130-am-89914.jpg"

    ]

  ]

  2 => array:1 [▼

    0 => array:2 [▼

      "destinationPath" => "images/"

      "filename" => "15-1-tue-apr-7-2020-130-am-30958.jpg"

    ]

  ]

  3 => array:1 [▼

    0 => array:2 [▼

      "destinationPath" => "images/"

      "filename" => "15-1-tue-apr-7-2020-130-am-68870.jpg"

    ]

  ]

]

如果我直接在刀片中调用照片,如下所示,它可以拉出图像:


  <img class="img-fluid options-item" src="{{$path}}/{{ $photos[0]['destinationPath'] }}{{ $photos[0]['filename'] }}" alt="">

但是当我尝试遍历数组时


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

  <img class="img-fluid options-item" src="{{$path}}/{{ $photos[$i]['destinationPath'] }}{{ $photos[$i]['filename'] }}" alt="">

@endfor

我收到以下错误:


Facade\Ignition\Exceptions\ViewException

Undefined index: destinationPath (View: C:\Apache24\htdocs\collection\proof\resources\views\pages\gallery.blade.php)

我还尝试了以下结果是否定的:


@foreach ($photos as $photo)

   <img class="img-fluid options-item" src="{{$path}}/{{ $photo['destinationPath'] }}{{ $photo['filename'] }}" alt="">

@endforeach

结果:


Facade\Ignition\Exceptions\ViewException

Undefined index: destinationPath (View: C:\Apache24\htdocs\collection\proof\resources\views\pages\gallery.blade.php)

任何关于正确语法的指导将不胜感激。


qq_花开花谢_0
浏览 90回答 1
1回答

绝地无双

在这里,您首先使用的是@for,但最终使用的是@endforeach。你想用哪一个?for循环还是foreach循环?@for ($i = 0; $i < count($photos); $i++)&nbsp; <img class="img-fluid options-item" src="{{$path}}/{{ $photos[$i]['destinationPath'] }}{{ $photos[$i]['filename'] }}" alt="">@endforeach如果你想使用foreach@foreach ($photos as $photo)&nbsp;<img class="img-fluid options-item" src="{{$path}}/{{ $photo->destinationPath }}{{ $photo->filename }}" alt="">@endforeach您收到错误的原因是$photo['destinationPath']数组语法。$photo实际上是object。所以你需要使用->来访问它的属性。
随时随地看视频慕课网APP
我要回答