0

我创建了一个将父子列表转换为“城市”类对象的函数:

   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') 时,我有一个没有结束的列表并且循环不会停止?

4

1 回答 1

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

}
于 2012-10-03T17:15:06.870 回答