PHP Если папка существует, выполните цикл для каждой подпапки - PullRequest
2 голосов
/ 29 сентября 2011

Я пытаюсь заставить мой код работать. Я в основном проверяю, что если папка существует, и в этой директории существует любая подпапка с именем 3 или более (3,4,5), то выполняю цикл, иначе ничего.

// the folder path
$folderPath="".cdnurl."assets/".pid."";
// looks like site.com/assets/342/

// is there a sub folder called 3 or more, 3,4,5 and loop from 3
// site.com/assets/342/3
// site.com/assets/342/4
// etc, we only loop if 3 exists other wise nothing

$folderSubNumber =>3;

    while(file_exists($folderPath.$folderSubNumber)) {

        echo '<li><img src="assets/pid/'.folderSubNumber.'';

    } else {

    // nothing 
        echo "";    
    }

Ответы [ 4 ]

3 голосов
/ 29 сентября 2011

Похоже, что вы должны это сделать.Просто измените это => на простое =, и не забудьте увеличить:

while (file_exists($folderPath.$folderSubNumber)) {
    echo '...';
    $folderSubNumber += 1;
}

(Кроме того, часть else не разрешена. Но она вам не нужнавот так ничего не потеряно.)

2 голосов
/ 29 сентября 2011

Простой метод:

$subdirs = glob(cdnurl . "assets/" . pid . "/*", GLOB_ONLYDIR);

, который вернет все подкаталоги в указанном каталоге. Ссылка: http://php.net/glob

1 голос
/ 29 сентября 2011

Приготовьтесь к конструктивной критике, пожалуйста.

В этом коде много неправильного.Сначала я добавлю комментарии, чтобы объяснить некоторые ошибки, а также некоторые бессмысленные вещи, которые ничего не делают.


$folderPath="".cdnurl."assets/".pid."";
// 1. Single-quotes will perform slightly better.
// 2. There is no need for the first "". or the final ."" - they do nothing.
// 3. Ideal: $folderPath = cdnurl.'assets/'.pid;
// 4. This assumes that cdnurl and pid are constants declared with the define() command. If they are not constants, you need dollar-signs, which would make it:
//    $folderPath = $cdnurl.'assets/'.$pid;

$folderSubNumber => 3;
// You cannot put a "more than X" or "less than X" in a variable. The => is used in foreach() loops for a completely different purpose, and when declaring values in an array only when the array is originally declared. (In other words; in this case, this does nothing.)

// Indentation really does matter. This should be indented the same as the code above.
while(file_exists($folderPath.$folderSubNumber)) {
    // 1. $folderSubNumber never changes and so this while-loop always asks the exact same question.
    // 2. You don't have a directory separator "/", so this will append $folderSubNumber straight to pid, above.

    echo '<li><img src="assets/pid/'.folderSubNumber.'';
    // 1. folderSubNumber needs a dollar-sign because it's a variable. If it is not defined as a constant, it will simply be the literal string "folderSubNumber".
    // 2. The appended .'' does nothing and shouldn't be there.
    // 3. You are neither closing the <img> tag, nor the <li> tag, nor in fact the src-attribute.
    // 4. Ideal: echo '<li><img src="assets/pid/'.$folderSubNumber.'" /></li>';

} else {
    // 1. There is no "else" in while.
    // 2. You don't need an "else" if the intention is to do nothing.

    echo "";
    // This is 100% pointless, it does nothing.
}

Что вам тогда нужно, это увеличить $ foldeSubNumber после того, как вы попробовали это вцикл while (см. ответ «sdleihssirhc»).Но также обратите внимание, что вам, вероятно, нужен разделитель каталогов между $ folderPath и $ folderSubNumber.Это было бы: $folderPath.'/'.$folderSubNumber

Удачи!

0 голосов
/ 03 октября 2011
// Build folder path
$folder_path = cdnurl . 'assets/' . $pid . '/';

// Loop from 3 to 5
for ($i = 3; i <= 5; $i++) {

  // Checking for a valid sub-directory
  // Will check sub-directory e.g.: site.com/assets/342/3/
  if ( is_dir($folder_path . $i . '/') ) {

    // Sub-directory exists
    echo $folder_path . $i;
  } else {

    // No Sub-directory, break out of for loop
    // This is will stop PHP for looking for sub-directory 4 or 5
    break;
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...