【问题标题】:Find rows matching values from array从数组中查找匹配值的行
【发布时间】:2016-02-22 22:18:22
【问题描述】:

我有一个表单,用户可以选择一个或多个这样的复选框:

{!! Form::Label('faults', 'Please select one of the following that best describes your device') !!}
                                            <div class="form-group">                                            
                                                @foreach($faults as $fault)
                                                <div class="col-md-4">
                                                    <span><i class="fa fa-question-circle" rel="popover" data-content="{{$fault->fault_tooltip}}"></i></span>
                                                    <label class="checkbox-inline">
                                                    <input id="faults" type="checkbox" name="faults[]" value="{{$fault->id}}">{{$fault->fault}}
                                                    </label>
                                                </div>
                                                @endforeach
                                            </div>

现在在我的控制器中,我得到了如下错误的输入:

$faults = Input::get('faults');

这会返回一个数组,其中包含每个故障的 ID,如下所示:

    array:2 [▼
  0 => "37"
  1 => "36"
]

我需要遍历数组并在故障表中找到与数组中的每个 id 匹配的每一行,并获取其他值,例如 $fault->name 和 $fault->price。

我知道这很容易,但我是从编码开始的,我无法理解。

任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: arrays laravel laravel-5.1


    【解决方案1】:
    $slectedFaults = Input::get('faults');
    

    如果您在 \App\ 目录中有故障模型,请按照以下方式进行操作

    $faults = Faults::whereIn('id',$slectedFaults)->get();
    

    或者按照以下方式做

     $faults = App\DB::table('faults')->whereIn('id',$slectedFaults)->get();
    

    $faults 已从您的数据库中选择数据,然后执行其余操作

    $nameArray = [];
    foreach($faults as $fault) {
      $nameArray[] = $fault->name;
      //do your thing here
    }
    print_r($nameArray); //it will print all fault names
    

    【讨论】:

      【解决方案2】:

      您有Faults 型号吗?如果是这样:

      $faults = Faults::findMany(Input::get('faults'));
      
      foreach($faults as $fault) {
         //do your thing here
      }
      

      否则用表格:

      $faults = DB::table('faults')
        ->select()
        ->whereIn('id',Input::get('faults'))
        ->get();
      
      foreach($faults as $fault) {
         //do your thing here
      }
      

      【讨论】:

      • 感谢您这么快回复!这行得通,但如果我尝试回显 $fault_name(在循环内:$fault_name = $fault->name;)我只会得到 1 个错误,但用户选择了两个。
      • 如果您在 for 循环之前执行 dd($faults),您会看到哪些/多少错误?
      猜你喜欢
      • 2019-08-17
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-02
      • 2014-11-07
      相关资源
      最近更新 更多