PHP显示提要项并按字母顺序列出,并在上方显示每个标题的首字母。它仅在整个列表上方显示一个字母,并且是Feed中第一个标题的字母。我出于隐私目的在此处更改了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(' & ', ' & ', $feed[$x]['title']);
echo '<li>';
echo '<a href="" title="'.$title.'" target="_blank">'.$title.'</a>';
echo '</li>';
}
echo '</ul>';
?>
答案 0 :(得分:0)
您确定标题首字母的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(' & ', ' & ', $feed[$x]['title']);
echo '<li>';
echo '<a href="" title="'.$title.'" target="_blank">'.$title.'</a>';
echo '</li>';
}
echo '</ul>'; // Close the last UL