2011-07-04 52 views
0

這裏的循環是否有循環更好的方法,雖然這種XML列表

function List($input) 
{ //I'm sure there's a better way of doing this... 
    $list = simplexml_load_string($input); 
    foreach($list->nation as $nation){ 
     foreach($nation->region as $region){ 
      $temp['url']= (string)$region['url']; 
      $temp['name'] = (string)$region['name']; 
      $temp['nation'] = (string)$nation['name']; 
      $out['regions'][] = $temp;    
     } 
     $temp['url'] = (string)$nation['url']; 
     $temp['name'] = (string)$nation['name']; 
     unset($temp['nation']); 
     $out['nations'][] = $temp; 
    } 
    return $out;   
} 

樣本數據:

<?xml version="1.0"?> 
<regions> 
    <nation url="canada" name="Canada" > 
    <region url="abbotsford" name="Abbotsford" /> 
    <region url="barrie" name="Barrie" /> 
    <region url="brantford" name="Brantford" /> 
    <region url="calgary" name="Calgary" /> 
    <region url="charlottetown" name="Charlottetown" /> 
</nation> 
<nation url="ireland" name="Ireland"> 
    <region url="cork" name="Cork"/> 
    <region url="dublin" name="Dublin"/> 
    <region url="galway" name="Galway"/> 
    <region url="limerick" name="Limerick"/> 
    <region url="waterford" name="Waterford"/> 
</nation> 

感謝所有幫助

+1

「更好「在什麼方面?也許嘗試http://codereview.stackexchange.com? – deceze

+0

更高效和/或更乾淨的代碼。我對未定的要求不滿意。 – Brad

回答

1
function List($input) { 
    $list = simplexml_load_string($input); 

    // guarantee fixed output format 
    $out = array('regions' => array(), 'nations' => array()); 

    foreach ($list->nation as $nation){ 
     foreach ($nation->region as $region){ 
      $out['regions'][] = array(
       'url' => $region['url'], 
       'name' => $region['name'], 
       'nation' => $nation['name'] 
      ); 
     } 

     $out['nations'][] = array(
      'url' => $nation['url'], 
      'name' => $nation['name'] 
     ); 
    } 

    return $out;   
} 
+0

爲什麼我不這樣想!我添加(字符串)到輸出,以便它不再是一個簡單的xml對象..但你的代碼完美工作以外的其他!而且乾淨! – Brad