Reputation: 6740
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?
Upvotes: 1
Views: 219
Reputation: 23880
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");
Upvotes: 4
Reputation: 101310
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
Upvotes: 4