PHP rss feed сортировать по алфавиту и отображать первую букву над заголовком - PullRequest
0 голосов
/ 19 ноября 2018

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

?>

1 Ответ

0 голосов
/ 19 ноября 2018

Ваш цикл 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...