找不到适合我需要的答案,
事实上,
我有一个实体类别,它与自己的关系为 One-To-Many, Self-referencing
我需要生成一个名为
的多维度命名值数组
样本数组:
Array
(
[Disaster] => Disaster
[Disaster_sub] => Array
(
[Natural] => Natural
[War] => War
)
[Techno] => Techno
[Tecno_sub] => Array
(
[IT] => IT
[IT_sub] => Array
(
[Dev] => Dev
[Bizz] => Bizz
)
)
)
我实际上尝试过的是
public function generateCategoryTree($entity, $arr = [])
{
$children = $entity->getChildren();
$parent = $entity->getParent();
$name = $entity->getName();
if(is_null($parent)) {
$parentName = $entity->getName();
$arr[$parentName] = $parentName;
}
if(!is_null($children)) {
foreach ($children as $child) {
$list[$name] = [$name => $name];
$this->generateCategoryTree($child, $arr);
}
}
return $arr;
}
然后在另一个函数中调用它,
$queryCategory = $this->entityManager->createQueryBuilder('c')
->select('c')
->from('CategoryBundle:Category', 'c')
->where('c.parent IS NULL')
->orderBy('c.root, c.lft', 'ASC');
$entities = $queryCategory->getQuery()->getResult();
$choices = [];
foreach ($entities as $key => $entity) {
$choices += $this->generateCategoryTree($entity, $choices));
}
我就在附近但没有实现, 有帮助吗?
答案 0 :(得分:0)
我已经解决了它,对于那些遇到相同问题的人,
这是工作代码
注意:
这里的实体类别具有根据Gedmo DoctrineExtensions
public function generateCategoryTree($entity, &$arr = [])
{
$children = $entity->getChildren();
$name = $entity->getName();
$arr += [(string)$entity => $entity->getId()];
if(count($children) > 0) {
$arr[$name.'_sub'] = [];
foreach($children as $child) {
$this->generateCategoryTree($child, $arr[$name.'_sub']);
}
}
return $arr;
}
然后我在这里调用此函数,
$choices = [];
foreach ($entities as $key => $entity) {
$this->generateCategoryTree($entity, $choices);
}