这是我的代码,它显示了我想要的结果,但是是否可以按顺序或
列出它们? $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的顺序显示的,而不是按时间显示的。
是否有一行代码我可以包括排序结果的日期变量?
首先是一些改进代码的一般提示:
foreach ($xml->sport[0]->event_path->event_path as $gameinfo):
是个坏主意。相反,我给你自己一个礼物,并给你一个新的变量(你可以稍后感谢我):
$gameinfos = $xml->sport[0]->event_path->event_path;
foreach ($gameinfos as $gameinfo):
现在要对$gameinfos
进行排序。这里的问题是,它们是迭代器而不是数组。uasort
函数(以及所有其他数组排序函数)将不再提供任何帮助。幸运的是,前面已经概述了这一点,您可以将迭代转换为数组:
$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.
PHP有非常有用的排序函数,可以定义用户比较函数。链接:http://www.php.net/manual/en/function.uasort.php
感谢您的宝贵时间!现在我的代码如下:
$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);
这只是返回一个结果,虽然,我认为我已经走错了一些地方沿线?