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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀