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

PHP rss feed sort alphabetically and display First letter above title

PHP 显示提要项目并按字母顺序列出它们并显示上面每个标题的首字母。它只在整个列表上方显示一个字母,它是提要中第一个标题的字母。出于隐私目的,我在这里更改了 feedurl。有什么想法吗?

    <?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>';

?>

确定标题第一个字母的 foreach 循环在实际打印它的 for 循环之外。因此,您总是要输出 foreach 循环的最后一个字母。

将该部分移到 for 循环中,例如

$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