我有150个对象的非常大的集合
...
App\almacen {#1679
id: 124,
emp_id: 1,
dst_id: 13,
hora: 0,
numMesa: 0,
event_id: 1,
created_at: "2018-01-22 11:41:03",
updated_at: "2018-01-22 11:41:03",
},
App\almacen {#1680
id: 125,
emp_id: 1,
dst_id: 11,
hora: 0,
numMesa: 0,
event_id: 1,
created_at: "2018-01-22 11:41:03",
updated_at: "2018-01-22 11:41:03",
},
App\almacen {#1681
id: 126,
emp_id: 1,
dst_id: 12,
hora: 0,
numMesa: 0,
event_id: 1,
created_at: "2018-01-22 11:41:03",
updated_at: "2018-01-22 11:41:03",
},
App\almacen {#1682
id: 127,
emp_id: 1,
dst_id: 20,
hora: 0,
numMesa: 0,
event_id: 1,
created_at: "2018-01-22 11:41:03",
updated_at: "2018-01-22 11:41:03",
},
App\almacen {#1683
id: 128,
emp_id: 1,
dst_id: 7,
hora: 0,
numMesa: 0,
event_id: 1,
created_at: "2018-01-22 11:41:03",
updated_at: "2018-01-22 11:41:03",
},
...
我必须比较密钥emp_id和dst_id是否等于例如8的数字并返回' true'如果它存在 有没有办法做到这一点,而不使用'foreach'直接看对象? 已经使用contains(),search()但总是返回' false'即使价值确实存在
答案 0 :(得分:2)
Firstwhere:
$exists = $items->firstWhere(['emp_id' => 8, 'dst_id' => 8]) !== null;
首先:
$needle = 8;
$exists = $items->first(function($item) use($needle) {
return $item->emp_id === $needle && $item->dst_id === $needle ;
}) !== null;
过滤器:
$needle = 8;
$exists = $items->filter(function($item) use($needle) {
return $item->emp_id === $needle && $item->dst_id === $needle ;
})->count() > 0;
答案 1 :(得分:2)
您可以像这样在where method
上使用collections
:
$collection = collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
['product' => 'Bookcase', 'price' => 150],
['product' => 'Door', 'price' => 100],
]);
$filtered = $collection->where('price', 100);
$filtered->all();
答案 2 :(得分:0)
firstWhere
(不起作用)
first:
$needle = 8;
$exists = $items->first(function($key, $item) use ($needle) {
return $item->emp_id === $needle && $item->dst_id === $needle ;
}) !== null;
filter
:
$needle = 8;
$exists = $items->filter(function($key, $item) use ($needle) {
return $item->emp_id === $needle && $item->dst_id === $needle ;
})->count() > 0;
答案 3 :(得分:-1)
就用
return $collection->where('price', '100')->toArray();