我有一堆数据存储在一个XML文件中,我用PHP打印出列表。我希望用户能够选择如何对列表进行排序。PHP usort()是否在DOM nodeLists上工作?
我用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 2012-01-03 10:22:18
唉,你说得对。我正在用“nodelist”进行搜索,这似乎滤除了很多相关的结果。 XSLT似乎是我应该去的方式。对不起,我会尽量在下次更有效地搜索。我应该删除这个问题吗? – 2012-01-03 12:28:44
好吧,如果搜索结果回答你的问题,那么是的,我会删除它。不知道你是否可以用@Sjoerd给出答案。 – Gordon 2012-01-03 12:39:11