防止选择字段中的重复值

时间:2016-07-19 07:03:04

标签: php laravel

我正在尝试比较下面的选择字段,以防止用户提交相同的水果名称。

例如

Field #1: Apple
Field #2: Apple 
Field #3: Banana  

到目前为止我的代码:

查看

<table class="table table-bordered">
        <thead>
           <th>Product</th>
           <th>Quantity</th>
        </thead>
        <tbody class="body">
        <tr>
           <td>{!! Form::select('fruits[]', $products, null, ['class'=>'form-control']) !!}</td>
           <td>{!! Form::text('quantity[]', null, ['placeholder' => 'Insert Quantity', 'class' => 'form-control']) !!}</td>
        </tr>
        <tr>
           <td>{!! Form::select('fruits[]', $products, null, ['class'=>'form-control']) !!}</td>
           <td>{!! Form::text('quantity[]', null, ['placeholder' => 'Insert Quantity', 'class' => 'form-control']) !!}</td>
        </tr>
        <tr>
           <td>{!! Form::select('fruits[]', $products, null, ['class'=>'form-control']) !!}</td>
           <td>{!! Form::text('quantity[]', null, ['placeholder' => 'Insert Quantity', 'class' => 'form-control']) !!}</td>
        </tr>
        </tbody>
    </table>

控制器

$products = ['Apple', 'Banana', 'Orange'];

$inputs = Input::all();

for ($i = 0; $i < count($inputs['fruits']); $i++) {

    if($inputs['fruits'][$i] == ????? ){ <-- Here is my problem

    return back();

    }
}

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

存储所选产品的临时变量怎么样?

$products = ['Apple', 'Banana', 'Orange'];

$inputs = Input::all();

$selected_products = [];
for ($i = 0; $i < count($inputs['fruits']); $i++) {
    $product = $inputs['fruits'][$i];

    if (isset($selected_products[$product]))
        return back();

    $selected_products[$product] = true;
}