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.'">'."
";
echo "\t".'<span class="name">'.$stop->StopName.'</span>'."
";
echo "\t".'<span class="arrow"></span>'."
";
echo '</a></li>'."
";
}
How (and where) can I sort the results to be listed alphabetically?
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");
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