doumen6532 2009-03-09 14:44
浏览 50
已采纳

如何对数组中的对象进行排序?

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?

  • 写回答

2条回答 默认 最新

  • duanjiaren8188 2009-03-09 15:03
    关注

    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");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!