【问题标题】:inner foreach loop check if condition and break only inner loop in php内部foreach循环检查条件并仅中断php中的内部循环
【发布时间】:2019-09-04 16:11:27
【问题描述】:

我有两个嵌套的 foreach 循环,我只希望内部循环检查条件。如果满足或不满足其中一个,则终止内循环并返回外循环。

在我的情况下,内循环总是需要运行一次,因为我理解我的问题。

问题:两个数组。首先拥有所有选项。第二只选择了。现在计算 id。如果匹配=> 打印检查,否则 => 未检查。

我已经尝试过休息;但内部循环仅检查第一项,然后执行 else 部分中的所有迭代。

@php
foreach($propertyAmenities as $amenity){
   foreach($property->amenities as $new){ 
        if( ($amenity->type == 'amenity') && ($amenity->id == $new->id) ){
        @endphp
        <label class="checkbox-inline control-label">
            <input type="checkbox" name="amenity[]" value="{{$amenity->id}}" {{'checked'}}>{{ $amenity->name }}
        </label>                         
        @php break;                       
          } 
        elseif(($amenity->type == 'amenity')){ @endphp
            <label class="checkbox-inline control-label">
                <input type="checkbox" name="amenity[]" value="{{$amenity->id}}">{{ $amenity->name }}
            </label> 
        @php break;
            }                                                                    
         }
      }
@endphp

第一次检查并在下一次仅执行 ifelse 部分时打印“已检查”。我不知道为什么 只检查第一个。

其他所有内容均未选中。

【问题讨论】:

  • amenities 中的$property-&gt;amenities 是关系方法吗?
  • 是的,这是一种关系

标签: php laravel


【解决方案1】:

您可以通过在视图中将所选选项作为数组传递来简化代码。


// Given $selectedOptions = [1, 2, 3, 4...]
@foreach($property->amenities as $amenity)
    <label class="checkbox-inline control-label">
        <input type="checkbox" 
               name="amenity[]" 
               value="{{$amenity->id}}"
               @if (in_array($amenity->id, $selectedOptions))
                   checked="checked"
               @endif
        >{{ $amenity->name }}
    </label>  
@endforeach

【讨论】:

  • 谢谢你爱你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 2016-09-26
  • 2012-07-19
  • 2017-05-28
  • 2015-10-30
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多