我创建了一个将父子列表转换为“城市”类对象的函数:
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') 时,我有一个没有结束的列表并且循环不会停止?