制作最新消息<b>旧</b>

时间:2013-11-27 03:03:56

标签: php

所以我想出了这个,这是一个新闻剧本。 这些文件的名称带有 [27.11.13]突发新闻!作为日期,而rsort会将它们全部反转以保持最新版本。 但问题是,我怎样才能使最后一个(最新的)有一个粗体标签? (我实际上想为它添加一些效果,所以把它加粗只是一个例子,我只需要指示)

<?php
$files = array();
if($handle = opendir( 'includes/news' )) {
    while( $file = readdir( $handle )) {
        if ($file != '.' && $file != '..') {
            // let's check for txt extension
            $extension = substr($file, -3);
            // filename without '.txt'
            $filename = substr($file, 0, -4);
            if ($extension == 'txt')
                $files[] = $filename; // or $filename
        }
    }
    closedir($handle);
}
rsort($files);
foreach ($files as $file)
    echo '<h2><a href="?module=news&read=' . $file 
        . '">&raquo; ' . $file . "</a></h2>";
}
?>

2 个答案:

答案 0 :(得分:0)

假设最后一个是从上到下在DOM中列出的第一个,你可以使用CSS:

h2:first-child {
   font-weight: bold;
}

或者我可能会做的事情因为可能有多个新的设置为新的h2类:

$todaysDate = date("d.m.y");
foreach ($files as $file) {
    $fileDate = substr($file,1,8);
    if ($todaysDate == $fileDate) {
       $today = true;
    }
    echo '<h2 class="news'.($today ? ' today' : '').'"><a href="?module=news&read=' . $file 
        . '">&raquo; ' . $file . "</a></h2>";
}

然后用CSS来设置新新闻的样式:

h2.news.today {
   font-weight: bold;
}

请注意,在您根据其他条件更改$ new变量之前,第二个选项将全部为粗体。您可能想要按日期或其他方式进行检查。

编辑:

$count = 0;
foreach ($files as $file) {
    $count++;
    echo '<h2 class="news'.($count === 1 ? ' latest' : '').'"><a href="?module=news&read=' . $file 
        . '">&raquo; ' . $file . "</a></h2>";
}

h2.news.latest {
   font-weight: bold;
}

你也可以使用for循环:

for ($count = 0; $count < count($files); $count++) {
    echo '<h2 class="news'.($count === 0 ? ' latest' : '').'"><a href="?module=news&read=' . $files[$count] 
        . '">&raquo; ' . $files[$count] . "</a></h2>";
}

答案 1 :(得分:0)

$files中的项进行计数,然后在循环执行时检查返回数组的键值。如果物品到达最后一个钥匙?大胆了。

<?php
$files = array();
if($handle = opendir( 'includes/news' )) {
    while( $file = readdir( $handle )) {
        if ($file != '.' && $file != '..') {
            // let's check for txt extension
            $extension = substr($file, -3);
            // filename without '.txt'
            $filename = substr($file, 0, -4);
            if ($extension == 'txt')
                $files[] = $filename; // or $filename
        }
    }
    closedir($handle);
}
rsort($files);
$last_key = count($files - 1);
foreach ($files as $file_key => $file_value)
    $file_final = '<a href="?module=news&read=' . $file . '">&raquo; ' . $file . '</a>';
    if ($file_key == $last_key) {
       $file_final = '<b>' . $file_final . '</b>';
    }
    echo '<h2>'
       . $file_final
       . '</h2>'
       ;
}
?>
相关问题