开发者

PHP Help with "if" statement to dynamically include files

I have these files:

"id_1_1.php", "id_1_2.php", "id_1_3.php" etc "id_2_1.php", "id_2_2.php", "id_2_3.php" etc

the number of files is not known because will always grow..

all the files are in same directory..

I want to make a if statement:

  1. to include the files only if their name ends with "_1"
  2. another function to load all the files that start with "id_1"

How can I do this? Thank you!

edit1: no the numbers will not be skipped, once I have another item for id_1_ collection of products I will add new ones as id_1_1, id_1_2开发者_开发技巧 etc.. so no skipping..


// 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');


Loosely based on Svisstack's original answer (untested):

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_');
}


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');
    }
}


This will parse through every file incrementing by one until it finds a file that doesn't exist. Assuming contiguous numbers it should catch every existing file. If you want to include files with a number other then 1 in the name, just change $lookingfor as appropriate.

$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++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜