在 Laravel 中循环 return view('pageName', [ loop]

我正在尝试使用insinde laravel 循环return view()来传递多个变量。这样就不需要对它们进行硬编码,这个列表有 30 个项目,它总是随机选择 8 个值。所以这是我的代码


 return view ( 'shop.landing' , [

            for($z = 0 ; $z <8 ;$z++){

                'productMatchesToMasterCategory' => ($masterCategoryList[$z]['name'].$productMatchesToMasterCategory);

            }

            'tomorrow' => Carbon::tomorrow () ,

这是快照

http://img2.mukewang.com/61d191ad0001143708690104.jpg

那么任何人都可以告诉我的代码有什么问题,还是不允许在内部使用循环view()



慕工程0101907
浏览 272回答 3
3回答

倚天杖

您不能在数组语法中使用循环。解决的办法是在外面构建数组,然后作为参数传递。我不确定您正在寻找的确切结构,但类似于这样:$data = [];for ($z = 0; $z < 8; $z++) {&nbsp; &nbsp; $data[] = ($masterCategoryList[$z]['name'] . $productMatchesToMasterCategory);}return view('shop.landing', [&nbsp; &nbsp; 'productMatchesToMasterCategory' => $data,&nbsp; &nbsp; 'tomorrow' => Carbon::tomorrow(),]);

烙印99

您应该在返回视图之前执行此操作:$productMatchesToMasterCategoryArray = [];for($z = 0; $z < 8; $z++) {&nbsp; &nbsp; $productMatchesToMasterCategoryArray[] = ($masterCategoryList[$z]['name'].$productMatchesToMasterCategory);&nbsp; &nbsp; &nbsp;}return view('shop.landing', [&nbsp; &nbsp; 'productMatchesToMasterCategory' => $productMatchesToMasterCategoryArray&nbsp; &nbsp; //Other variables here]);希望能帮助到你。

小怪兽爱吃肉

您可以尝试在返回视图之前获取随机 8 个元素的数组。$productMatchesToMasterCategoryArray = [];foreach($masterCategoryList as $z){&nbsp; &nbsp; $productMatchesToMasterCategoryArray[] = ($z['name'].$productMatchesToMasterCategory);}$random_Array=array_rand($productMatchesToMasterCategoryArray,8);return view('shop.landing', [&nbsp; &nbsp; 'productMatchesToMasterCategory' => $random_Array,&nbsp; &nbsp; 'tomorrow' => Carbon::tomorrow(),]);
打开App,查看更多内容
随时随地看视频慕课网APP