PHP按字母顺序解析XML并对子节点进行排序

时间:2012-06-29 10:18:27

标签: php xml sorting

我有一个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>";

2 个答案:

答案 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>';

答案 1 :(得分: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>";

它是一个盲目的......应该工作。