我有这些文件:
“id_1_1.php”,“id_1_2.php”,“id_1_3.php”等 “id_2_1.php”,“id_2_2.php”,“id_2_3.php”等
文件数量未知,因为它总是会增长..
所有文件都在同一个目录中..
我想制作一个if语句:
我该怎么做?谢谢!
edit1:不会跳过这些数字,一旦我为id_1_系列产品添加了另一个项目,我会将新的项目添加为id_1_1,id_1_2等等。所以不要跳过..
答案 0 :(得分:1)
function my_include($f, $s)
{
@include_once("id_" . $f . "_" . $s . ".php");
}
function first_function($howmany = 100, $whatstart = '1')
{
for ($i=1; $i <= $howmany; $i++)
{
my_include('1', $i)
}
}
function second_function($howmany = 100, $whatend = '1')
{
for ($i=1; $i <= $howmany; $i++)
{
my_include($i, '1');
}
}
答案 1 :(得分:1)
基于Svisstack的原始答案(未经测试):
function doIncludes($pre='',$post=''){
for ($i=1;1;$i++)
if (file_exists($str=$pre.$i.$post.'.php'))
include($str);
else
return;
}
function first_function(){
doIncludes('id_','_1');
}
function second_function(){
doIncludes('id_1_');
}
答案 2 :(得分:1)
这将解析每个递增1的文件,直到找到不存在的文件。假设连续数字,它应该捕获每个现有文件。如果您想在名称中包含除1以外的数字的文件,只需根据需要更改$ lookingfor。
$lookingfor = 1;
$firstnum=1;
while ($firstnum>0) {
$secondnum=1;
while ($secondnum>0) {
$tempfilename = "id_".$firstnum."_".$secondnum.".php";
if file_exists($tempfilename) {
if (($firstnum==$lookingfor)||($secondnum==$lookingfor)) {include $tempfilename; }
$secondnum++;
} else {
$secondnum=-1;
}
}
$firstnum++;
}
答案 3 :(得分:1)
// Each of these:
// - scans the directory for all files
// - checks each file
// - for each file, does it match the pattern described
// - if it does, expand the path
// - include the file once
function includeFilesBeginningWith($dir, $str) {
$files = scandir($dir);
foreach ($files as $file) {
if (strpos($file, $str) === 0) {
$path = $dir . '/' . $file;
include_once($path);
}
}
}
function includeFilesEndingWith($dir, $str) {
$files = scandir($dir);
foreach ($files as $file) {
if (strpos(strrev($file), strrev($str)) === 0) {
$path = $dir . '/' . $file;
include_once($path);
}
}
}
/* To use: - the first parameter is ".",
the current directory, you may want to
change this */
includeFilesBeginningWith('.', 'id_1');
includeFilesEndingWith('.', '_1.php');