繁体   English   中英

比较两个数组键值

[英]Compare two array key values

我有以下代码, $tables包含系统中所有可用的表, $order_info包含所有当前订单,其中也包含 table_id,

现在我只想显示那些 table_id 不在$order_info数组中的表。

@foreach($tables as $t)
@foreach($order_info as $o)
    @if($o['table_id'] != $t->table_id)
        <option value="{{$t->table_id}}">{{$t->table_number}}</option>
    @endif
@endforeach
@endforeach

显然上面的代码向我显示了重复的表格编号,因为我正在为两个 arrays 循环它,我怎样才能只显示那些不在$order_info中的表格

谢谢,

你必须这样写你的代码 -

@foreach($tables as $item)   
    @if(! in_array($item->table_id,array_column($order_info,'table_id')))
       <option value="{{$item->table_id}}">{{$item->table_number}}</option>
    @endif   
@endforeach

或者

@foreach($tables as $item)   
    @if(array_search($item->table_id, array_column($order_info,'table_id')) == false)
       <option value="{{$item->table_id}}">{{$item->table_number}}</option>
    @endif   
@endforeach

感谢朋友的帮助,在Laravel中找到了一些简单的方法,

@foreach($tables as $t)
    @if (! $order_info->contains('table_id', $t->table_id))
        <option value="{{$t->table_id}}">{{$t->table_number}}</option>
    @endif
@endforeach

直接在Controller中执行该操作会更容易

我想你有两个模型OrderTable ,你已经像这样定义了这两个模型之间的关系

class Table extends Model {
    public function oders(){
        return $this->hasMany('Order');
    }
}

class Order extends Model {
    public function table(){
        return $this->belongsTo('Table');
    }
}

因此,在渲染执行循环的view的控件中,您可以像这样渲染顺序

public function ...() {

    $order_info = Order::where('...', '')->get();
   
    $tables = Table::whereDoesntHave('order', function($query){
        $query->whereNotIn('id', $order_info->pluck('id'));
    });
    
    return view('...', compact('tables', 'order_info'); 
}

在这里,由于您已经拥有order_info列表,因此您只能返回具有给定id的订单不存在的表

$tables = Table::whereDoesntHave('order', function($query){
    $query->whereIn('id', $order_info->pluck('id'));
});

在这里,我使用pluck返回order_info表中的orders id数组。

实际上它不会返回重复项。 第一个循环

@foreach($tables as $t)

@endforeach

它将返回一个值,然后第二个循环将开始,它将前一个值与 order_info 中的所有值进行比较。 . 再次第一个循环将返回一个值。 然后第二个循环将对第一个循环返回的每个单独的值进行迭代。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM