【问题标题】:How to sort XML feed using PHP如何使用 PHP 对 XML 提要进行排序
【发布时间】:2009-11-19 11:58:52
【问题描述】:

我是解析 xml 提要的新手;所以我有一段我一直在处理的代码,它从 xml 文件中提取数据。现在我希望能够按发布日期 pubdate 对数组进行排序。我没有找到任何可以帮助我的例子。

我使用了 sort(),它以某种随机顺序排列。

$xml_headline_key = "*ARRAY*CATCHUP*PROGRAMMENAME";
$xml_link_key = "*ARRAY*CATCHUP*ITEMURL";
$xml_description_key = "*ARRAY*CATCHUP*SHORTSYNOPSIS";
$xml_publish_key = "*ARRAY*CATCHUP*ORIGINALAIRINGDATE";
$story_array = array();
$counter = 0;
class xml_story{
 var $headline, $description, $link, $pubdate;
}
function contents($parser, $data){
 global $current_tag, $xml_headline_key, $xml_link_key, $xml_description_key, $counter, $story_array, $xml_link_key, $xml_publish_key;
 switch($current_tag){
  case $xml_headline_key:
   $story_array[$counter] = new xml_story();
   $story_array[$counter]->headline = $data;
   break;
  case $xml_link_key:
   $story_array[$counter]->link = $data;
  break;
  case $xml_description_key:
   $story_array[$counter]->description = $data;
   $counter++;
   break;
  case $xml_publish_key:
   $story_array[$counter]->pubdate = $data;
  break;
  }
}

$corrie_counter = 0;
sort($story_array);
$dateformat = "D j M, g:ia";

for($x=0;$x<count($story_array);$x++){
 if($story_array[$x]->headline == "Coronation Street"){
 if($corrie_counter != 4){
 echo "<li><span class=\"bold\">". date($dateformat, strtotime($story_array[$x]->pubdate)) . "</span>\n";
echo "\t<span class=\"text\">" . trunc($story_array[$x]->description,30, " ") . "</span>\n";

回显 "\t"; $corrie_counter++; } } }

【问题讨论】:

  • 如果你想节省一些时间,我强烈推荐magpie rss解析器。 magpierss.sourceforge.net
  • @shane 这看起来像 rss 但 xml !== rss

标签: php xml


【解决方案1】:

您可以使用uasort,并在sortByPubdate 中定义两个pubdates 的比较方式。

uasort($story_array, 'sortByPubdate');
// Sort function
function sortByPubdate($a, $b) {
    if ($a->pubdate == $b->pubdate) {
        return 0;
    }
    return ($a->pubdate < $b->pubdate) ? -1 : 1;
}

【讨论】:

  • 谢谢,没用内容和以前一样,其实是sort();实际上比 uasort 排序更多。还有什么我需要用uasort添加的我错过了什么吗????哦,是的,我将它包含在 for 循环的上方。
  • $story_array 是否可能已经按日期排序?只需尝试按不同的字段(可能是标题)对其进行排序。另请查看文档php.net/manual/en/function.uasort.php
猜你喜欢
  • 1970-01-01
  • 2022-10-15
  • 2012-05-30
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多