1

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?

2 Answers 2

4

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");
Sign up to request clarification or add additional context in comments.

1 Comment

This worked like a charm! I've actually tried several variants of this code, and this - the simplest one - worked!
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.