arrays - 如何检查我的 Object PersistantCollection 中是否存在值?
问题描述
我的对象“字段”:
array:4 [▼
0 => Fields {#10900 ▶}
1 => Fields {#11222 ▶}
2 => Fields {#11230 ▼
-id: 8
-name: "Tier"
-uuid: "5f60107fe4"
-productgroup: PersistentCollection {#11231 ▶}
-options: PersistentCollection {#11233 ▶}
-template: PersistentCollection {#11235 ▼
-snapshot: []
-owner: Fields {#11230}
-association: array:20 [ …20]
-em: EntityManager {#4288 …11}
-backRefFieldName: "fields"
-typeClass: ClassMetadata {#7714 …}
-isDirty: false
#collection: ArrayCollection {#11236 ▼
-elements: []
}
#initialized: true
}
-type: Type {#11237 ▶}
-formatstring: ""
}
3 => Fields {#11511 ▶}
]
我想知道“字段”中是否存在某个“templateId”:
foreach ($fields as $field) {
$templateId = $field->getTemplate();
$result = property_exists($templateId, 3);
}
结果是“假的”,即使我希望它是真的。
解决方案
首先,
$templateId = $field->getTemplate();
返回模板的 ArrayCollection(顺便说一下,您应该重命名属性模板)
我相信您要做的是检查模板是否在字段的数组模板中。
所以有两种正确的方法来做到这一点:
使用Doctrine\Common\Collections\ArrayCollection中的contains方法
将一个对象与另一个对象进行比较
//First get the proper Template object instead of the id
$template = $entityManager->getRepository(Template::class)->find($templateId);
$templateArray = $field->getTemplate();
//return the boolean you want
$templateArray->contains($template);
比较索引/键:
$templateArray = $field->getTemplate();
//return the boolean you want
$templateArray->containsKey($templateId);
但是如果你想做同样的事情,但使用另一个属性而不是 id 你可以遍历你的数组:
比较其他属性
//In our case, name for example
$hasCustomAttribute=false;
foreach($field->getTemplate() as $template){
if($template->getName() == $nameToTest){
$hasCustomAttribute=true;
}
}
推荐阅读
- sql-server - Can't install sql server on amazon linux instance - Requires: systemd-units systemd and numactl-libs
- java - How to return List with Streams in this case?
- c# - Why is TextMeshPro not Updating textBounds After Setting text?
- multi-tenant - 在 aspnetboilerplate 中查看每个租户
- sql - 如何在 date_trunc 中添加整数变量
- python - 限制绝地中的python版本或关键字
- excel - Matching and pulling values
- java - 为什么插页式广告让我返回首页?
- react-native - 从 Web 服务获取图像会出错
- java - Do we have to free an allocated ByteBuffer manually?