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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作