私はXMLファイルに格納された一連のデータをPHPでリストとして出力しています。私は、ユーザーがリストのソート方法を選択できるようにしたい。PHPのusort()はDOMノードリストで動作しますか?
usort()
で少し実験しましたが、動作していないようです。それは例外を投げるわけではないので、私はそれが実行可能だと思っていますが、私のソート機能には何か面白いことがあります。私がやりたいまず最初は、データが作成された日付でソートさせている - これは、このように属性に格納されています
<root>
<info created="2011-12-31">
<sometags />
</info>
<info created="2012-01-02">
<sometags />
</info>
<info created="2012-01-01">
<sometags />
</info>
</root>
と私のソートはこれで行われます
function sortByDate($a, $b) {
//get array of year, month and day
$adates = explode('-', $a->getAttribute('created'));
$bdates = explode('-', $b->getAttribute('created'));
//if the years are not the same, use them to sort
if ($adates[0] != $bdates[0]) {
return (intval($adates[0]) < intval($bdates[0])) ? -1 : 1;
}
//if the years are the same, try sorting by the months
else if ($adates[1] != $bdates[1]) {
return (intval($adates[1]) < intval($bdates[1])) ? -1 : 1;
}
//if the years and months are both the same, try sorting by days
else {
return (intval($adates[2]) < intval($bdates[2])) ? -1 : 1;
}
//if we get this far, the dates are identical
return 0;
}
これは、私はそれを呼び出す方法です:
$xmlDoc = new DOMDocument();
$xmlDoc->load('data.xml');
$infotags = $xmlDoc->documentElement->getElementsByTagName('info');
usort($infotags, 'sortByDate');
は、それは私が作った、または私は完全に何かをやるべきいくつかの愚かな誤りですか?
ところで、上記のif... else
構造は実際には正しい順序で日付を並べ替えるわけではないことを認識しています。私はちょうどそれをやろうとしている何か - 現時点でusort()
は、それが始まったのと同じ順序でノードリストを残します。
質問する前にhttp://stackoverflow.com/search?q=sort+xml+phpのいずれかをチェックしましたか?もしそうなら、あなたの質問に答えられなかった理由を教えてください。 – Gordon
ああ、そうです。私は "nodelist"で検索していました。これは関連性の高い結果をたくさん除外しているようです。 XSLTは私が行かなければならない方法のようです。申し訳ありませんが、私は次回より効果的に検索しようとします。この質問を削除する必要がありますか? –
検索結果があなたの質問に答えたら、それを削除します。あなたが@Sjoerdと答えることができるかどうかは分かりません。 – Gordon