gpt4 book ai didi

arrays - 如何检查我的对象PersistantCollection中是否存在值?

转载 作者:行者123 更新时间:2023-12-01 12:06:57 26 4
gpt4 key购买 nike

我的对象“字段”:

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);
}

结果为“假”,即使我期望它为真。

实体字段列表: https://pastebin.com/zcuFi1dE

模板: https://pastebin.com/mVkKFwJr

最佳答案

首先,

$templateId = $field->getTemplate();

返回模板的ArrayCollection(通过这种方式,您应该重命名属性Templates)

我相信您要做的是检查模板是否在字段的 template 数组中。

因此,有两种正确的方法可以做到这一点:

使用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;
}
}

关于arrays - 如何检查我的对象PersistantCollection中是否存在值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com