Marc
Marc

Reputation: 559

Sorting Results returned by SimpleXML, and Xpath in PHP

I get and display the results from the XML like so:

<?php
    $xml = simplexml_load_file($url);
    //RUN QUERY ON XML
    $xQuery = $xml->xpath($query);

foreach($xQuery as $results){
?>
        MAKE:  <?php echo $results->Make;?><br />
        Model: <?php echo $results->Model;?><br />
   <?php } ?>

Now what I would like to do is sort the $xQuery to for instance display the results of the Make's in alphabetical order before I display it.

Is this possible? If so how can I manage this?

Upvotes: 1

Views: 1429

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

You can probably do it with XPath or something, but SimpleXMLElement::xpath() returns an array that is easy to sort:

usort($xQuery, function ($a, $b) { return strcmp($a->Make, $b->Make); });
foreach ($xQuery as $results) {
    // …
}

Upvotes: 1

Related Questions