0

我有一堆数据存储在一个 XML 文件中,我用 PHP 将其打印为一个列表。我希望用户能够选择如何对列表进行排序。

我尝试了一点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()只是按照与开始时相同的顺序离开节点列表。

4

1 回答 1

0

getElementsByTagName返回一个 DOMNodeList,它是一个迭代器,而不是一个真正的数组。因此,您不能更改列表的顺序。

尝试先将其转换为数组。

于 2012-01-03T10:12:38.633 回答