2012-06-29 121 views
0

我有一個XML文件並將其解析到我的PHP文檔中。我想按照字母順序排列我的XML的子節點,並在我的選擇框中顯示它們。有人可以幫幫我嗎?我被困在分揀過程中... :)PHP解析XML並按字母順序排序子節點

country.xml

<?xml version="1.0"?> 
<countries> 
    <country> 
     <name>Deutschland</name> 
     <league>Bundesliga</league> 
    </country> 
    <country> 
     <name>Frankreich</name> 
     <league>Ligue 1</league> 
    </country> 
    <country> 
     <name>Osterreich</name> 
     <league>Tipp3-Bundesliga</league> 
    </country> 
    <country> 
     <name>England</name> 
     <league>Premier League</league> 
    </country> 
    <country> 
     <name>Schweden</name> 
     <league>Allsvenskan</league> 
    </country> 
    <country> 
     <name>Kanada</name> 
     <league>Canadian Soccer League</league> 
    </country> 
</countries> 

我的PHP代碼如下:

echo "<select>";  
foreach ($newXml as $item) { 
    $country=$item->name; 
    $league=$item->league; 
    echo $league; 
    echo "<option>".$country."-".$league."</option>"; 
} 
    echo "</select>"; 
+0

按字母順序排列的是什麼?國家還是聯盟? –

回答

1

可以分三個步驟做到這一點:

// 1. collect 
foreach ($newXml as $country) { 
    $items[] = "{$country->name} - {$country->league}"; 
} 
// 2. sort (on country and league in this case) 
sort($items); 
// 3. enumerate 
echo '<select>'; 
foreach ($items as $item) { 
    echo '<option>', htmlspecialchars($item), '</option>'; 
} 
echo '</select>'; 
0

您可以在創建選擇框之前使用數組。

echo "<select>";  
$temp = array() 
foreach ($newXml as $item) 
    $temp [$item->name] = $item->league; 

ksort($temp); 
foreach ($teml as $name => $league) { 
    $country=$name; 
    $league=$league; 
    echo $league; 
    echo "<option>".$country."-".$league."</option>"; 
} 
    echo "</select>"; 

它的一個盲注......應該工作。