马上我就知道这里已经有很多关于使用Glob()来提供foreach循环的线程。我已经阅读了我能找到的每一个,我仍然有困难,所以我想我会在这里发布我的代码,以防我错过了一些东西。
我的目标:使用foreach循环将HTML页面包装在一些标记中,并在我的页面上显示它们。我本来可以直接把HTML写进我的页面,但是我预计在接下来的几周里会有很多变化和添加,我担心版本重叠(这里不能使用版本控制)。
到目前为止,我有这个脚本拉入页面并显示它们,但IF逻辑没有触发。我哪里做错了?
<?php
$directory = 'includes/pages';
$dirIT = new DirectoryIterator($directory);
try {
// Pull in HTML files from directory
foreach ( $dirIT as $key => $item ) {
if ($item->isFile()) {
if ( $key == '0')
{
echo "<div class='"one-third column alpha'">";
$path = $directory . "/" . $item;
include $path;
echo "</div>";
}
elseif ($key == count ( dirIT ) - '1' )
{
echo "<div class='"one-third column omega'">";
$path = $directory . "/" . $item;
include $path;
echo"</div>";
}
else
{
echo "<div class='"one-third column'">";
$path = $directory . "/" . $item;
include $path;
echo "</div>";
}
}
}
}
catch(Exception $e) {
echo 'There are no pages to display.<br />';
}
?>
在下面的else if
语句中,您有一个小的错别字,并且没有使用实际的变量:
elseif ($key == count ( dirIT ) - '1' )
dirIT
应为$dirIT
。尝试更新到以下内容,看看是否有帮助:
elseif ($key == (count($dirIT) - 1))
旁注:因为$dirIT
在你的循环中不会改变,你可以在进入循环之前预先计数它,以防止每次重新计数。例如,您可以使用:
$dirITCount = (count($dirIT) - 1);
foreach ( $dirIT as $key => $item ) {
...
} else if ($key == $dirITCount) {
正如@newfurniture所说,问题是由elseif
行缺少$
引起的。
我建议这样重写你的代码:
$g = glob('includes/pages/*.html');
$c = count($g);
if( $c > 0) {
foreach ( $g as $key => $item ) {
echo '<div class="one-third column';
if( $key == 0) echo ' alpha';
if( $key == $c-1) echo ' omega';
echo '">';
include $item;
echo '</div>';
}
}
else {
echo 'There are no pages to display.<br />';
}
最有可能的问题是在您的isFile()
函数。尝试使用简单的本地(http://php.net/manual/en/function.is-file.php) is_file()
函数来检查特定项目是否为文件。