2012-10-03 123 views
0

我ceated一個函數來父子的列表轉換爲類「城市」的目標:轉換對象數組

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

現在我向創造一個功能反其道而行之=>轉換對象類型級城市爲一個數組,所以我做這樣的:

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(「$結果」),所以我有一條沒有盡頭的列表,循環就不停止?

+0

它看起來像你試圖插入數組到一個數組索引。這是正確的'$ result ['childrens'] = array($ key_child => $ child);'看起來這可能會給我帶來麻煩。 – Malachi

+0

你有解決方案嗎? – Nll

+0

那麼最好的條件是停止遞歸? – Nll

回答

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

}