使用simpleXML进行PHP排序问题

时间:2010-06-11 13:18:04

标签: php simplexml

的test.xml:

<?xml version="1.0"?>
<props>
<prop>
<state statename="Mississippi">
    <info>
        <code>a1</code>
        <location>Jackson</location>
    </info>
    <info>
        <code>d2</code>
        <location>Gulfport</location>
    </info>
    <info>
        <code>g6</code>
        <location>Hattiesburg</location>
    </info>
</state>
<state statename="Texas">
    <info>
        <code>i9</code>
        <location>Dallas</location>
    </info>
    <info>
        <code>a7</code>
        <location>Austin</location>
    </info>
</state>
<state statename="Maryland">
    <info>
        <code>s5</code>
        <location>Mount Laurel</location>
    </info>
    <info>
        <code>f0</code>
        <location>Baltimore</location>
    </info>
    <info>
        <code>h4</code>
        <location>Annapolis</location>
    </info>
</state>
</prop>
</props>

test.php的     

// start the sortCities
function sortCities($a, $b){
    return strcmp($a->location, $b->location);
}
// start the sortStates
function sortStates($t1, $t2) {
    return strcmp($t1['statename'], $t2['statename']);
}


$props = simplexml_load_file('test.xml');
foreach ($props->prop as $prop) {
    $sortedStates = array();
    foreach($prop->state as $states) {
        $sortedStates[] = $states;
        }
    usort($sortedStates, "sortStates"); // finish the sortStates
    /* --- */
    echo '<pre>'."\n";
    print_r($sortedStates);
    echo '</pre>'."\n"; 
    /* --- */
    foreach ($prop->children() as $stateattr) { // this doesn't do it
    //foreach($sortedStates as $hotel => @attributes){ // blargh!
        if(isset($stateattr->info)) {
            $statearr = $stateattr->attributes();
            echo '<optgroup label="'.$statearr['statename'].'">'."\n";
            $options = array();
            foreach($stateattr->info as $info) {
                $options[] = $info;                            
            }
            usort($options, "sortCities"); // finish the sortCities  
            foreach($options as $stateattr => $info){
                echo '<option value="'.$info->code.'">'.$info->location.'</option>'."\n";
            }
            echo '</optgroup>'."\n";
            } else {
                //empty nodes don't do squat
            }
    }
}  
?>

这是以下数组:

print_r($sortedStates);

打印出来:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [statename] => Maryland
                )

            [info] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [code] => s5
                            [location] => Mount Laurel
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [code] => f0
                            [location] => Baltimore
                        )

                    [2] => SimpleXMLElement Object
                        (
                            [code] => h4
                            [location] => Annapolis
                        )

                )

        )

    [1] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [statename] => Mississippi
                )

            [info] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [code] => a1
                            [location] => Jackson
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [code] => d2
                            [location] => Gulfport
                        )

                    [2] => SimpleXMLElement Object
                        (
                            [code] => g6
                            [location] => Hattiesburg
                        )

                )

        )

    [2] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [statename] => Texas
                )

            [info] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [code] => i9
                            [location] => Dallas
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [code] => a7
                            [location] => Austin
                        )

                )

        )

)

这样:

// start the sortCities
function sortCities($a, $b){
    return strcmp($a->location, $b->location);
}

加上这部分代码:

    $options = array();
    foreach($stateattr->info as $info) {
        $options[] = $info;                            
    }
    usort($options, "sortCities"); // finish the sortCities  
    foreach($options as $stateattr => $info){
        echo '<option value="'.$info->code.'">'.$info->location.'</option>'."\n";
    }

通过每个optgroup中的“位置”节点进行排序很好。

你可以看到在数组中我可以按属性'statename'进行排序。我遇到的问题是回应和组合这两个函数,以便自动对状态和城市进行排序,并形成所需的选择组。

我尝试复制城市的线路并更改名称,但有几种方法无济于事。

因此,使用上面的XML结构,我试图让它看起来像:

<optgroup label="Maryland">
<option value="h4">Annapolis</option>
<option value="f0">Baltimore</option>
<option value="s5">Mount Laurel</option>
</optgroup>
<optgroup label="Mississippi">
<option value="d2">Gulfport</option>
<option value="g6">Hattiesburg</option>
<option value="a1">Jackson</option>
</optgroup>
<optgroup label="Texas">
<option value="a7">Austin</option>
<option value="i9">Dallas</option>
</optgroup>

无论在XML中按顺序排列状态的顺序如何,无论在状态中的节点中如何排序位置,它们总是在创建optgroup时按字母顺序排序。


Artefacto -

最后2个代码块显示按名称(位置节点)对节点进行排序的功能。


// start the sortCities
function sortCities($a, $b){
    return strcmp($a->location, $b->location);
}
// start the sortStates
function sortStates($t1, $t2) {
    return strcmp($t1['statename'], $t2['statename']);
}

第二个函数按数组中的属性(statename)进行排序,但是,将两个函数组合在一起,或者更确切地说将它们嵌套,以便按字母顺序对状态和城市进行排序让我感到难过。


@Artefacto,

感谢您的回复。似乎有意义的嵌套方式。问题是,我的服务器都没有运行PHP 5.3。因此泛型函数抛出错误。我应该提到这一点,但没想到。他们正在运行5.2。我一直试图恢复脚本,并且已经陷入了一个部分。

<?php
$doc = simplexml_load_file('test.xml');
$states =  get_object_vars($doc->prop->children());
$states = $states["state"];
function sortStates($t1, $t2) { 
    return strcmp($t1['statename'], $t2['statename']); 
};
usort($states, "sortStates");

/* this is just here for testing */
echo '<pre>';
print_r($states);
echo '</pre>';
/* end testing */

/*
array_walk($states,
    function (&$state) {
        $state = get_object_vars($state);
        array_walk($state["info"],
            function (&$el) {
                $el = get_object_vars($el);
            }
        );
        usort($state["info"],
            function($a, $b) { return strcmp($a["location"], $b["location"]); }
        );
    }
);
*/
?>

以array_walk开头的注释掉的部分。我无法弄清楚如何在下一行死亡时重写'function(&amp; $ state)'。

3 个答案:

答案 0 :(得分:2)

您希望根据某些属性或元素值对SimpleXMLElement列表进行排序。您通常通过将列表转换为数组然后对该数组应用排序来执行此操作。

PHP中有用的功能是iterator_to_array。它的工作就是将simplexml中那些神奇的东西变成一个更“固定”的数组。

让我们在$result->tour中说出你的旅游元素。默认情况下,simplexml在这里返回一个迭代器,这是你不能开箱即用的东西。让我们把它转换成一个数组:

$tours = iterator_to_array($result->tour, false);

现在$tours变量是一个数组,其中包含<tour>元素作为SimplXMLElement。您现在可以使用数组函数对该数组进行排序。那些array sorting functions are outlined in the PHP manual和我通常建议How do I sort a multidimensional array in php作为一个很好的起点:

$tourDates = array_map(
    function($tour) {return trim($tour->next_bookable_date); },
    $tours
);

// sort $tours array by dates, highest to lowest
$success = array_multisort($tourDates, SORT_DESC, $tours);

而且已经是这样了。整个代码一目了然:

$tours = iterator_to_array($result->tour, false);

$tourDates = array_map(
    function($tour) {return trim($tour->next_bookable_date); },
    $tours
);

// sort $tours array by dates, highest to lowest
$success = array_multisort($tourDates, SORT_DESC, $tours);

foreach ($tours as $tour) {
    ...
}

答案 1 :(得分:1)

我的方法是将SimpleXMLElement对象转换为数组:

$doc = new SimpleXMLElement($xml);
$states =  get_object_vars($doc->prop->children());
$states = $states["state"];
usort($states, function($t1, $t2) { return strcmp($t1['statename'], $t2['statename']); });
array_walk($states,
    function (&$state) {
        $state = get_object_vars($state);
        array_walk($state["info"],
            function (&$el) {
                $el = get_object_vars($el);
            }
        );
        usort($state["info"],
            function($a, $b) { return strcmp($a["location"], $b["location"]); }
        );
    }
);

答案 2 :(得分:0)

更改此

foreach ($prop->children() as $stateattr)

到这个

foreach ($sortedStates as $stateattr)

做到了。

可能已经发誓我已经尝试过了。

相关问题