dongqiuge5435 2016-04-12 18:49
浏览 92
已采纳

在foreach laravel外面使用变量

I have a problem with Laravel. So what am I trying to do? I'm trying to get the location from all my examples. This actually works, so as you can see I get the id of all the examples and find the locations of it from another table in my project. The var_dump in the foreach gives what I need. But I need this data outside the foreach, I need to send it to my view afterwards. But the second var_dump, the one outside the foreach only gives the location of the first id.

So my question: is there a way to get the full $locations outside the foreach.

$ids= DB::table('example')
            ->select('id')
            ->get();

        foreach($ids as $id)
        {
            $locations = example::find($id->id)->locations()->get();
            var_dump($locations);
        }

        var_dump($locations);

This is my view:

 @foreach($examples as $example)
   <h1>{{$example->name}}</h1>
   @foreach($locations as $location)
     {{$location}}
   @endforeach
@endforeach

I see al the locations from al the $examples in every $example if I print it like this, I hope you understand my question.

  • 写回答

2条回答 默认 最新

  • dongyu9850 2016-04-12 18:57
    关注

    Try this:

    // Define locations array
    $locations = [];
    
    // Then do the following for each example:
    
    // Define the array for locations of each example outside of the loop
    $locations[$example->name] = [];
    
    foreach ($ids as $id) {
        // Add each location to the $locations array
        $locations[$example->name][] = example::find($id->id)->locations()->get();
    }
    

    Or if you want to get a little bit more fancy, you can use array_map instead of foreach:

    $locations[$example->name] = array_map(function ($id) {
        return example::find($id->id)->locations()->get();
    }, $ids);
    

    Then in the view, you simply take out the locations from the right key for each example:

    @foreach ($examples as $example)
        <h1>{{ $example->name }}</h1>
        @foreach ($locations[$example->name] as $location)
            {{ $location }}
        @endforeach
    @endforeach
    

    You don't have to use the $example->name as the key, just make sure it's unique for each example you want to fetch locations for.

    I hope this helps.

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

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图