views:

153

answers:

2

I have searched and found a couple of solutions on this site, that didn't work for me. My case is that I perform a XPath search (contains function) in the XML, and lists the results. I want those results listed alphabetically. The results are laying in an array, and looks like this:

Array
(
    [0] => SimpleXMLElement Object
        (
            [DISID] => 2160364
            [StopName] => Nationtheatret
        )

    [1] => SimpleXMLElement Object
        (
            [DISID] => 1118735
            [StopName] => Huldrefaret
        )

    [2] => SimpleXMLElement Object
        (
            [DISID] => 2200752
            [StopName] => Jernbanetorget
        )
)

I am listing the data like this:

$xml = new SimpleXMLElement(file_get_contents("StopPointList.xml"));

$query = strtolower($_GET["q"]);

$upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ";
$lower = "abcdefghijklmnopqrstuvwxyzæøå";

$result = $xml->xpath("//StopPoint[contains(translate(StopName, '$upper', '$lower'), '$query')]");

foreach ($result as $stop)
{
    echo '<li><a href="stops.php?id='.$stop->DISID.'">'."\n";
    echo "\t".'<span class="name">'.$stop->StopName.'</span>'."\n";
    echo "\t".'<span class="arrow"></span>'."\n";
    echo '</a></li>'."\n";
}

How (and where) can I sort the results to be listed alphabetically?

+4  A: 

It looks like in your foreach loop you will need to copy the data into another data structure, sort that structure, and then output it. These functions may help

Tom Ritter
+3  A: 

In order to sort the objects, you'll need a comparison function. For example, to compare by StopName, use something like this:

function cmp ($a, $b)
{
    return strcmp($a->StopName, $b->StopName);
}

Then, after your xpath query and before the foreach, add this line to do the actual sorting:

usort($result, "cmp");
Pesto
This worked like a charm! I've actually tried several variants of this code, and this - the simplest one - worked!
rebellion