将Object转换为数组

时间:2012-10-03 16:53:27

标签: php symfony

我停止了一个函数,将父子列表转换为类“city”的对象:

   public static function createCity(array $config)
{
    $city= new City();

    $id=key($config);
    $label= $config[$id]['label'];

    $city->setId($id);
    $city->setLabel($label);

    $children = $config[$id]['childrens'];

    if(!empty($children)){
        foreach($children as $key_child => $child) {
            $children = array($key_child => $child);

            $city->addChild(self::createCity($children));

        }
    }
  return $city;
}

现在我要创建一个函数来执行相反的操作=>将Class City类型的对象转换为数组,所以我喜欢这样:

   public function getCityArray(City$rootCity)
{
        $result = array();

        $result['id'] = $rootCity->getId();
        $result['label']= $rootCity->getLabel();

    $children = $rootCity->getChildren();


    if ( !empty($children)) {
        foreach ($children as $key_child => $child) {

            $result['childrens'] = array($key_child => $child );

            $result[] = $this->getCityArray($child);
        }
    }

    return $result;

}

但它不起作用,因为当我执行var_dump('$ result')所以我有一个没有结束的列表而且循环没有停止?

1 个答案:

答案 0 :(得分:0)

试试这个。由于我不知道有完整的代码,不知道它是否会起作用。类变量$result将包含结果。

$result = array();
public function getCityArray(City $rootCity) {

  $result['id'] = $rootCity->getId();
  $result['label']= $rootCity->getLabel();
  $children = $rootCity->getChildren();

  if ( !empty($children)) {
    $result['childrens'] = $children;
    $this->result[] = $result;
    foreach ($children as $key_child => $child) {
      $this->getCityArray($child);
    }
  }

}