Php 在foreach循环中包含文件
在foreach循环中不可能使用PHP include吗 我有一个名为Php 在foreach循环中包含文件,php,foreach,include,Php,Foreach,Include,在foreach循环中不可能使用PHP include吗 我有一个名为$posts的文件名数组: Array ( [3] => post-an-example-post.html [4] => post-my-first-test-post.html [5] => post-my-second-test-post.html ) 我想为数组中的每个项目输出这些内容(一些简单的HTML): foreach ($posts as $post){
$posts
的文件名数组:
Array ( [3] => post-an-example-post.html
[4] => post-my-first-test-post.html
[5] => post-my-second-test-post.html )
我想为数组中的每个项目输出这些内容(一些简单的HTML):
foreach ($posts as $post){
$post = "/posts/" . $post;
echo $post;
include $post;
}
这给了我一个错误,因为它不会使用我添加的开头/
,而是保留在同一个文件中:
Warning: include(/posts/post-an-example-post.html): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/quick-blog/showposts.php on line 7
这些文件都存储在/posts/目录中
编辑:下面是如何创建数组$posts的。它扫描目录并删除任何不是以posts-
function postArray(){
$dir = 'posts';
$files = scandir($dir);
$posts = array_filter(
$files,
function($value) {
return (strpos($value, 'post-') === 0);
}
);
return $posts;
}
这是可能的,我经常扫描一个给定的文件夹中的文件,循环并包含每个文件。我觉得你的阵型很像 不应该是字符串吗?您还可以执行以下操作:)
)您为
包含提供了一个绝对位置。它在文件系统的顶部寻找一个名为posts
的目录,而不是文档根。首先,如果在数组上执行foreach($posts as$post),那么post将是数组的键。阵列必须如下所示:
$posts = Array ( 3 => "post-an-example-post.html",
4 => "post-my-first-test-post.html",
5 => "post-my-second-test-post.html",
);
现在尝试使用此数组如何生成数组字符串?请看,我在文件名周围添加了引号:)您可以发布整个代码吗?嗨,我的数组不是这样生成的,我添加了创建数组的函数。啊,这是第一个正斜杠:$post=“/posts/”谢谢!我太傻了,没问题。你能把这个答案标记为接受吗?;-)
$posts = Array ( 3 => "post-an-example-post.html",
4 => "post-my-first-test-post.html",
5 => "post-my-second-test-post.html",
);