【问题标题】:Use variable outside foreach laravel在 foreach laravel 之外使用变量
【发布时间】:2016-04-12 18:49:11
【问题描述】:

我对 Laravel 有疑问。那我想做什么?我正在尝试从我的所有示例中获取位置。这实际上是有效的,所以你可以看到我得到了所有示例的 id,并从我项目中的另一个表中找到它的位置。 foreach 中的 var_dump 提供了我需要的东西。但是我需要在 foreach 之外使用这些数据,之后我需要将它发送到我的视图中。但是第二个var_dump,foreach外的那个只给出了第一个id的位置。

所以我的问题是:有没有办法在 foreach 之外获取完整的 $locations。

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

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

        var_dump($locations);

这是我的看法:

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

如果我这样打印,我会在每个 $example 中看到所有 $examples 中的所有位置,希望您能理解我的问题。

【问题讨论】:

  • 那么你只想得到一个位置还是给定 id 的所有位置的数组?
  • 一个数组 :) 我想在视图中 foreach 它

标签: php laravel foreach


【解决方案1】:

试试这个:

// 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();
}

或者如果你想更花哨一点,你可以使用array_map而不是foreach

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

然后在视图中,您只需从每个示例的右键中取出位置:

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

您不必使用 $example-&gt;name 作为键,只需确保它对于您要为其获取位置的每个示例都是唯一的。

我希望这会有所帮助。

【讨论】:

  • 这在控制器端有效。但我不知道如何在视图中显示位置我想将该位置链接回示例。我想循环视图中的示例,但我无法从每个示例的数组中获取位置。希望你能理解我的问题。
  • 您能否将您视图中的代码添加到问题中?
  • 我更新了我的答案,如果您需要更多说明,请告诉我。
【解决方案2】:

无需构建$locations 数组。您可以很好地使用视图中的关系。

在您的控制器中:

// whatever your logic is to get the examples
$examples = example::with('locations')->get();

在你看来:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    相关资源
    最近更新 更多