【问题标题】:Loop inside Laravel return view('pageName', [ loop] gives me an errorLaravel 内部循环返回视图('pageName',[循环] 给我一个错误
【发布时间】:2020-01-09 19:39:04
【问题描述】:

我正在尝试使用 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 () ,

这是快照

那么谁能告诉我的代码有什么问题,还是不允许在view() 中使用循环?

谢谢

【问题讨论】:

    标签: php laravel loops for-loop


    【解决方案1】:

    您不能在数组语法中使用循环。 解决方法是在外面构建数组,然后将其作为参数传递。我不确定您正在寻找的确切结构,但类似这样:

    $data = [];
    
    for ($z = 0; $z < 8; $z++) {
        $data[] = ($masterCategoryList[$z]['name'] . $productMatchesToMasterCategory);
    }
    
    return view('shop.landing', [
        'productMatchesToMasterCategory' => $data,
        'tomorrow' => Carbon::tomorrow(),
    ]);
    

    【讨论】:

      【解决方案2】:

      您应该在返回视图之前执行此操作:

      $productMatchesToMasterCategoryArray = [];
      for($z = 0; $z < 8; $z++) {
          $productMatchesToMasterCategoryArray[] = ($masterCategoryList[$z]['name'].$productMatchesToMasterCategory);     
      }
      
      return view('shop.landing', [
          'productMatchesToMasterCategory' => $productMatchesToMasterCategoryArray
          //Other variables here
      ]);
      

      希望对你有帮助。

      【讨论】:

        【解决方案3】:

        您可以尝试在返回视图之前获取随机 8 个元素的数组。

        $productMatchesToMasterCategoryArray = [];
        foreach($masterCategoryList as $z){
            $productMatchesToMasterCategoryArray[] = ($z['name'].$productMatchesToMasterCategory);
        }
        $random_Array=array_rand($productMatchesToMasterCategoryArray,8);
        return view('shop.landing', [
            'productMatchesToMasterCategory' => $random_Array,
            'tomorrow' => Carbon::tomorrow(),
        ]);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-24
          • 2015-04-26
          • 2022-11-28
          • 2017-02-27
          • 1970-01-01
          相关资源
          最近更新 更多