Sorting Results returned by SimpleXML, and Xpath in PHP

余生长醉 提交于 2019-12-11 05:09:23

问题


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?


回答1:


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) {
    // …
}


来源:https://stackoverflow.com/questions/10936879/sorting-results-returned-by-simplexml-and-xpath-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!