dsrbb20862 2014-05-16 15:43
浏览 90
已采纳

Laravel - 传递具有多个相同标题的数组

So I went over this thread to figure out how to send data from controller to a view here.

However I am trying to pass multiple values with identical titles to the view and I cannot seem to figure out how to do this and still access them later.

I have a for loop that grabs all the films a user has in their database, this information is then stored into a array called $data

        $data = array();
        foreach ($films as $film)
        {               
            $title = $film->title;
            $description = $film->description;
            $url = $film->fileUrl;
            $data = array_add($data, 'title', $title);
            $data = array_add($data, 'description', $description);
            $data = array_add($data, 'url', $url);
        }
    $this->layout->content = View::make('profileFilms')->with($data);

This works but I cannot figure out how to access this information, I tried making each "film" its own array with all three data values and then adding that to the larger array and then passing that array to the view, which again worked but I cannot figure out how to access the data. if i use say {{$title}} it will grab one title, but I have no way of getting both.

How can I pass N number of films each with its title, description and url to a view so I can display them, and how can I display them?

  • 写回答

2条回答 默认 最新

  • drhwb470572 2014-05-16 15:53
    关注

    You are adding the values directly to the array once and that is it, because Laravels array_add only overwrites non existing keys.

    You should do something like that (or use Eloquent):

    <?php
    $data = array();
    foreach ($films as $film){
        $data['films'][] = array(
            'title' => $film->title,
            'description' => $film->description,
            'url' => $film->fileUrl
        );
    }
    $this->layout->content = View::make('profileFilms')->with($data);
    

    Then you can access your films (Blade style):

    @foreach($films as $film)
        {{$film['title']}}
    @endforeach
    

    If you want to use it like $film->title you can use the (object) typecast while assigning the array.

    Of course, you could also pass $films directly like

    $data = array(
        'films' => $films
    );
    

    Then you can access your films like you would in the controller. You can alsways use print_r and var_dump to see, what the variable really contains.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂