2013-04-04 50 views
0

这里是我的代码,显示结果我之后,但有可能通过以列出它们或订货XML的foreach导致PHP

$xml = simplexml_load_file('racing.xml'); 

    foreach ($xml->sport[0]->event_path->event_path as $gameinfo): 

    $description  = $gameinfo->description; 
    $getdate   = $gameinfo->event['date']; 
    $event_id   = $gameinfo->event['id']; 
    $date    = substr($getdate,0,10); 

代码

<?=substr($description, -5)?> 

给我留下与时间的变量,即:14:40,15:50:14:20:18:40等等,但它们按XML的顺序而不是按时间显示。

是否有一行代码可以包含在日期变量中排序结果?

回答

0

首先是一些一般的提示,以提高你的代码:

foreach ($xml->sport[0]->event_path->event_path as $gameinfo): 

是一个坏主意。所以,现在你想将$gameinfos排序

$gameinfos = $xml->sport[0]->event_path->event_path; 
foreach ($gameinfos as $gameinfo): 

:相反,我让自己的礼物,并给予一个新的变量(你可以感谢我以后)。这里的问题是那些是一个迭代器而不是一个数组。 uasort函数(以及所有其他数组排序函数)将不会对您有所帮助。幸运的是这has been outlined already,你可以迭代转换为数组:

$gameinfos = iterator_to_array($gameinfos, FALSE); 

现在$gameinfos是可以排序的数组。要做到这一点获取定义排序次序(其中$gameinfos应该进行排序)的值,我以为这是你上面写的时间substr($description, -5)

$order = array(); 
foreach ($gameinfos as $game) 
    $order[] = substr($game->description, -5) 
; 

array_multisort($order, $gameinfos); 

// $gameinfos are sorted now. 
+0

谢谢,我已经添加了一个答案,以显示代码! – Kris 2013-04-09 11:20:28

0

感谢您的时间!我现在有我的代码为:

$xml = simplexml_load_file('racing.xml'); 

    $gameinfos = $xml->sport[0]->event_path->event_path; 
    foreach ($gameinfos as $gameinfo): 

    $gameinfos = iterator_to_array($gameinfos, FALSE); 

    $order = array(); 
    foreach ($gameinfos as $game) 
    $order[] = substr($game->description, -5) ; 

    array_multisort($order, $gameinfos); 

    // $gameinfos are sorted now. 

    $description  = $gameinfo->description; 
    $getdate   = $gameinfo->event['date']; 
    $event_id   = $gameinfo->event['id']; 
    $date    = substr($getdate,0,10); 

这只是返回一个结果,但我想我已经走错了一些沿线?