php - 在 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)
任何有关正确语法的指导将不胜感激。
控制器:
class GalleryController extends Controller
{
function index($coin_id)
{
$coin = Coin::select('photos', 'mint', 'year', 'series', 'rating')
->where('id', '=', $coin_id)
->where('user_email', '=', auth()->user()->email)
->first();
$photos=$coin->photos;
$path=url('/');
dd($photos);
return view ('pages.gallery', compact('coin', 'photos', 'path'));
}
}
解决方案
在这里,您首先使用的是@for
,但最终使用的是@endforeach
. 你想用哪一个?for
循环还是foreach
循环?
@for ($i = 0; $i < count($photos); $i++)
<img class="img-fluid options-item" src="{{$path}}/{{ $photos[$i]['destinationPath'] }}{{ $photos[$i]['filename'] }}" alt="">
@endforeach
如果你想使用foreach
@foreach ($photos as $photo)
<img class="img-fluid options-item" src="{{$path}}/{{ $photo->destinationPath }}{{ $photo->filename }}" alt="">
@endforeach
您收到错误的原因$photo['destinationPath']
是数组语法。$photo
实际上是object
。所以你需要使用->
它来访问它的属性。