Symfony2:将检索到的对象转换为数组(并转储变量以进行故障排除)


Symfony2: Convert retrieved objects to array (and dumping variables for troubleshooting)

我有一个实体类别,它链接到自身以形成树(一个类别可以有一个类别作为父类别,一个类别可以有一堆类别作为子类别)。它们在实体内标记为私有,并且不向序列化程序公开。

当我做$category->getChildren()->toArray()时,我得到一个子数组,但是当我做$this->getDoctrine()->getRepsitory('PmbLicensing:Category')->findByParent($category)->toArray()时,我得到一个错误,toArray()没有定义。我需要使用后者,因为顶级类别的父类别设置为 null,所以我无法使用前一种方法。如何将后一种方法中获得的类别集合转换为数组?

此外,在尝试排除故障时,我经常想打印出变量,但是当我执行诸如print_r($categories);print_r((array)$categories);var_dump($categories);之类的操作时,调用只会运行大约两分钟,然后返回 null。我认为这是因为关系映射进入无限循环,但是我如何阻止这种情况发生?

编辑:我想将对象(或对象的集合)转换为数组,因为我想构建一个递归函数,其中所提供类别的子类别可以检索到 n 深度。如果提供的类别可以为空,以便从类别的主级别检索(父级设置为 null)。这是我的函数:

private function getRecursiveChildren(Category $category = null, $depth, $iteration)
{   
    $children = $this->getDoctrine()->getRepository('PmbLicensingBundle:Category')->findByParent($category);
    // 'Doctrine'Common'Util'Debug::dump($children); die();
    if ($depth > $iteration)
        foreach ($children as $child) {
            $child['children'] = $this->getRecursiveChildren($child, $depth, $iteration+1);
    }
    return $children;
}

在有$child['孩子']的行上,说我不能将对象用作数组。

如果您需要将结果作为数组形式返回,则可以将它们作为数组从数据库中返回。

在您的CategoryRepository课上:

public function findArrayByParent($categoryId) 
{ 
    // it's a good adivce from @i.am.michiel to pass only the `id` here. 
    // You don't need the whole category object.
    $query = $this->getEntityManager()->createQuery('...')
        ->setParameters(array('categoryId' => $categroyId));
    return $query->getArrayResult();
}

从数据库检索后,它们永远不会转换为对象,因此您还可以节省时间和内存。

其实你的

$children = $this->getDoctrine()->getRepository('PmbLicensingBundle:Category')
                                ->findByParent($category);` 

已经返回了一个数组,因此您不必(也不能)使用 ->toArray() .

当您使用

foreach ($children as $child)
    $child["..."] = ...

您正在将一个 obect $child视为一个带有 ["..."] 的数组。这就是您的错误消息的内容。


如果可以的话,你可能应该使用教义,让它填充相关的子类别和父类别。请参阅有关此的教义文档。然后,您自动拥有所有子项,并且可以像$category->getChildren()一样访问它们(这将返回一个ArrayCollection)。这将为您节省大量工作。

您的调用不会返回任何类别。顺便说一句,我认为您应该传递类别的 id,而不是实体。

$this->getDoctrine()
     ->getRepository('PmbLicensing:Category')
     ->findByParent($category->getId());

为什么要使用 toArray() 函数?ArrayCollection 已经是带有一些附加方法的数组?每当使用数组时,您应该能够使用 ArrayCollection。