基于XML数据重新排序XML结果

时间:2013-03-04 14:51:35

标签: php xml api xml-parsing

我们正在通过他们的API从远程服务器获取数据。不幸的是,他们的API没有按日期对返回的数据进行排序。

我正在尝试,但没有太大成功,弄清楚如何重新组织数据,以便next_bookable_date对它进行排序。我们使用PHP和SimpleXMLElement来解析数据并创建一个字符串,然后将其插入到网页中。但是当前结果与返回的XML中显示的数据顺序相同。

基本的XML结果如下。有更多的数据,我为了节省空间而剥离了。

SimpleXMLElement Object
(
    [request] => GET search.xml?start_date=2013-05-03&end_date=2013-05-17
    [error] => OK
    [total_tour_count] => 4
    [tour] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [next_bookable_date] => 2013-05-13
                    [tour_name] => Thailand Tour
                )
            [1] => SimpleXMLElement Object
                (
                    [next_bookable_date] => 2013-05-12
                    [tour_name] => Bali Tour
                )
            [2] => SimpleXMLElement Object
                (
                    [next_bookable_date] => 2013-05-05
                    [tour_name] => Hawaii Tour
                )
            [3] => SimpleXMLElement Object
                (
                    [next_bookable_date] => 2013-05-06
                    [tour_name] => Bhutan Tour
        )
    )
)

我们用来生成html字符串的PHP代码(再次删除了一些html代码以节省空间):

foreach($result->tour as $tour) {
$tourname = $tour->tour_name;
$tourdate = $tour->next_bookable_date;

// create string for dpt-soon
$dpt_soon_list .= "<li> some html using the above values </li>\n";
}

一旦我们从远程服务器收到XML数据,是否有办法重新排序?或者有没有办法在运行foreach时重新排序PHP输出?

1 个答案:

答案 0 :(得分:1)

您可以使用usort()对多维数组或对象进行排序。我写了这段代码来解释如何在SimpleXML中使用它:

<?php
// Load the XML file
$xml = simplexml_load_file("xml.xml");
// Get all children into an array
$Tours = (array)$xml->children();
$Tours = $Tours["tour"];

// Call usort on the array
usort($Tours, "sorttours");

// Output results
echo "<pre>".print_r($Tours, true)."</pre>";

// The function that specifies when an entry is larger, equal or smaller than another
function sorttours($a, $b) {
    // Parse strings into a date for comparison
    $Date1 = strtotime($a->next_bookable_date);
    $Date2 = strtotime($b->next_bookable_date);

    // If equal, return 0
    if ($Date1 == $Date2) {
        return 0;
    }
    // If Date1 is larger, return 1, otherwise -1
    return ($Date1 > $Date2) ? 1 : -1;
}
?>

此示例假定XML看起来像这样:

<?xml version="1.0"?>
<tours>
    <tour>
        <next_bookable_date>2013-05-13</next_bookable_date>
        <tour_name>Thailand Tour</tour_name>
    </tour>
    <tour>
        <next_bookable_date>2013-05-12</next_bookable_date>
        <tour_name>Bali Tour</tour_name>
    </tour>
    <tour>
        <next_bookable_date>2013-05-05</next_bookable_date>
        <tour_name>Hawaii Tour</tour_name>
    </tour>
    <tour>
        <next_bookable_date>2013-05-06</next_bookable_date>
        <tour_name>Bhutan Tour</tour_name>
    </tour>
</tours>

如果不是这种情况,那么您需要重写 sorttours 函数以使用例如用于确定订单的属性。

相关问题