donglaogu3788 2018-11-18 23:53
浏览 41
已采纳

PHP rss按字母顺序排序并显示标题上方的第一个字母

PHP to display feed items and list them alphabetically and display first letter of each title above. It is only show one letter above the whole list and it is the letter of the first title on the feed. I changed feedurl here for privacy purposes. Any Ideas?

    <?php
$rss = new DOMDocument(); 
$feed = array();
$urlArray = array(array('url' => 'https://feeds.megaphone.fm/SH')
);

foreach ($urlArray as $url) {
    $rss->load($url['url']);

    foreach ($rss->getElementsByTagName('item') as $node) {
        $item = array ( 
            'title' => $node->getElementsByTagName('title')->item(0)->nodeValue
            );
        array_push($feed, $item);
    }
}
usort( $feed, function ( $a, $b ) {
            return strcmp($a['title'], $b['title']); 
});
$previous = null;
foreach($item as $value) {
    $firstLetter = substr($value, 0, 1);
    if($previous !== $firstLetter) 
    $previous = $firstLetter;

}
$limit = 3000;
echo '<p>'.$firstLetter.'</p>';
echo '<ul style="list-style-type: none;>"';
for ($x = 0; $x < $limit; $x++) {
    $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);

    echo '<li>';
    echo '<a href="" title="'.$title.'" target="_blank">'.$title.'</a>';
    echo '</li>';
}
echo '</ul>';

?>
  • 写回答

1条回答 默认 最新

  • doujianzi8521 2018-11-19 00:32
    关注

    Your foreach loop that determines the first letter of the title is outside the for loop that actually prints it. Therefore, you are always going to output the last letter of the foreach loop.

    Move that part inside the for loop, something like

    $limit = 3000;
    $previous = null;
    $count_firstletters = 0;
    for ($x = 0; $x < $limit; $x++) {
        $firstLetter = substr($feed[$x]['title'], 0, 1); // Getting the first letter from the Title you're going to print
        if($previous !== $firstLetter) { // If the first letter is different from the previous one then output the letter and start the UL
            if($count_firstletters != 0) {
                echo '</ul>'; // Closing the previously open UL only if it's not the first time
            }
            echo '<p>'.$firstLetter.'</p>';
            echo '<ul style="list-style-type: none;>"';
            $previous = $firstLetter;
            $count_firstletters ++;
        }
        $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
    
        echo '<li>';
        echo '<a href="" title="'.$title.'" target="_blank">'.$title.'</a>';
        echo '</li>';
    }
    echo '</ul>';  // Close the last UL
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?