Laravel 5.2循环如何防止重复结果?

时间:2016-10-23 06:11:16

标签: laravel

Scenario是包含少数城市的区域,我的编辑表单存在问题。

问题是我需要在默认选项中将城市地带设为区域selected=true和另一个不属于区域的城市。

所以我有2个像这样的循环

@foreach($cities as $city)
    @foreach($zone->cities as $zone_city)
        @if($city->id == $zone_city->id)
            <option value="{{ $city->id }}" selected="true">{{ $city->name }}</option>
        @endif  
    @endforeach
//if current city id not yet printed before then
<option value="{{ $city->id }}">{{ $city->name }}</option>
@endforeach

$cities是从控制器传递的所有城市,其值为1, 2, 3, 4, 5,而$zone->cities是属于区域的城市,值为1, 3, 5

使用上面的代码我得到了这个结果

<option value="1" selected="true">Surabaya</option>
<option value="1">Surabaya</option>     
<option value="2">Sidoarjo</option>

<option value="3" selected="true">Malang</option>
<option value="3">Malang</option>

<option value="4" selected="true">Gresik</option>
<option value="4">Gresik</option>       
<option value="5">Madura</option>

我预期的结果是

<option value="1" selected="true">Surabaya</option>
<option value="2">Sidoarjo</option>

<option value="3" selected="true">Malang</option>

<option value="4" selected="true">Gresik</option>
<option value="5">Madura</option>

如何修复循环代码逻辑?

谢谢,任何帮助表示赞赏。

已更新

这是我的编辑控制器

public function zone_edit($id)
{
    $zone = Zone::find($id);
    $cities = City::all();
    return view('backend.admin.pricings.zone_edit', compact('zone', 'cities'));
}

2 个答案:

答案 0 :(得分:0)

你可以这样工作:

@foreach($cities as $city)
$currentCity = false;
@foreach($zone->cities as $zone_city)
    @if($city->id == $zone_city->id)
        $currentCity = true;
        <option value="{{ $city->id }}" selected="true">{{ $city->name }}</option>
    @endif  
@endforeach
//if current city id not yet printed before then
@if($currentCity)
<option value="{{ $city->id }}">{{ $city->name }}</option>
@endif
@endforeach

但我认为这是一种更好的方法,适合您的需要。

@foreach($cities as $city)
    @foreach($zone->cities as $zone_city)
        <option value="{{ $city->id }}" @if($city->id == $zone_city->id) selected="true" @endif  >{{ $city->name }}</option>
    @endforeach
@endforeach

答案 1 :(得分:0)

你可以试试这个

在控制器的功能

 $zoneCityIds = [];
 $zone = Zone::find($id);
 $cities = City::all();

 foreach ($zone->cities as $zoneCity)
 { 
  $zoneCityIds[] = $zoneCity->id
 }

 return view('backend.admin.pricings.zone_edit', compact('zone', 'cities','zoneCityIds'));

在您的视图中修改整个循环,如下所示

@foreach($cities as $city)
   <option value="{{ $city->id }}" @if(in_array($city->id, $zoneCityIds)) selected @endif>{{ $city->name }}</option>
@endforeach

希望这会有所帮助:)