如何按日期排序PHP简单XML树

时间:2011-09-22 21:53:23

标签: php xml simplexml

我正在浏览XML树,如下所示:

$notesXML = simplexml_load_string(XMLSTRING);

foreach($notesXML as $thenote){
  $noteAttr = $thenote->attributes();
  echo $noteAttr['modified'];
}

正如您所看到的,有一个名为“modified”的属性作为XML树的一部分,我现在要做的就是根据修改日期以升序或降序打印出XML树。 BTW日期字符串的格式如下:“2011年9月6日星期二03:49:14”

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您可以构建要排序的元素数组,然后使用其中一个array sorting functions重新排序。


下面的代码段使用array_multisort()按日期降序排序。 DateTime::createFromFormat()用于从日期字符串中获取Unix时间戳。

$notes = array();
$dates = array();
foreach ($notesXML as $note) {
    $notes[] = $note;
    $dates[] = DateTime::createFromFormat('l jS \of F Y H:i:s A', $note['modified'])->getTimestamp();
}
array_multisort($dates, SORT_DESC, $notes);

// Loop over $notes however you like