我有对象数组
$states = $this->getDoctrine()->getRepository(LocationState::class)->findAll();
如何检查$states
是否包含带有数据的对象?
LocationState {#102960 ▼
-id: 1
-ident: "02"
-name: "NAME"
-country: LocationCountry {#102992 ▶}
}
这不是 ArrayCollection,而是 Array of Objects。
对于对象数组:
$found = !empty(array_filter($objects, function ( $obj ) {
return $obj->name == 'NAME' && $obj->id == 1;
}));
对于 ArrayCollection:
$found = $objects->exists(function ( $obj ) {
return $obj->name == 'NAME' && $obj->id == 1;
});
如果您希望查询检索它们:
$this->getDoctrine()->getRepository(LocationState::class)
->findBy(['name' => 'NAME', 'ident' => '02']);
如果您只想知道指定的对象是否在您的集合中,则必须使用一些代码
$states = $this->getDoctrine()->getRepository(LocationState::class)->findAll();
$found = false;
foreach($state in $states) {
if($state->getName() == 'NAME' && $state->getIdent() == '02' ) {
$found = true;
}
}
学说2 数组集合过滤方法