如何使这个PHP代码更有效地运行?

时间:2014-03-11 12:38:47

标签: php html foreach scandir

PHP代码:

$AutomaticallyOpenShow = $AutomaticallyOpen."/";
$images = scandir($AutomaticallyOpen,0);
$counter = 0;
foreach($images as $curimg) {
        if (strpos($curimg, '.jpg')>0 || strpos($curimg, '.JPG')>0) {

                if($counter==1){$ImageView_1 = $AutomaticallyOpenShow.$curimg; }
            elseif($counter==2){$ImageView_2 = $AutomaticallyOpenShow.$curimg; }
            elseif($counter==3){$ImageView_3 = $AutomaticallyOpenShow.$curimg; }
            elseif($counter==4){$ImageView_4 = $AutomaticallyOpenShow.$curimg; }


        $counter++;
}
}   

HTML code:

<img src="<?php echo ImageView_1 ; ?>" width="500" height="500" />

感谢Kurro1和RaggaMuffin-420的回答。 我终于进行了整合

PHP代码:

$AutomaticallyOpenShow = $AutomaticallyOpen."/";
$images = scandir($AutomaticallyOpen,0);
$counter = 1;
foreach($images as $curimg) {

  if (preg_match('/^.*\.[jpeg]{3,4}$/i', $curimg)) {

$ImageView[$counter++] = $AutomaticallyOpenShow.$curimg;

$counter++;
  }
}

HTML code:

<img src="<?php echo $ImageView[????] ; ?>" width="500" height="500" />

3 个答案:

答案 0 :(得分:0)

根据您发布的第一个代码。

PHP代码:

$AutomaticallyOpenShow = $AutomaticallyOpen."/";
$images = scandir($AutomaticallyOpen,0);
$ImageView = Array();
$counter = 0;

foreach($images as $curimg) {
        if (strpos($curimg, '.jpg')>0 || strpos($curimg, '.JPG')>0) {
            $ImageView[$counter++] = $AutomaticallyOpenShow.$curimg;
    }
}   

HTML code:

<img src="<?php echo ImageView[0] ; ?>" width="500" height="500" />

答案 1 :(得分:0)

如何使用数组存储而不是4个变量?:

$AutomaticallyOpenShow = $AutomaticallyOpen."/";
$images = scandir($AutomaticallyOpen,0);
$counter = 0;
$ImageView = array();
foreach($images as $curimg) {
        // the condition could also be optimized
        if (strpos($curimg, '.jpg')>0 || strpos($curimg, '.JPG')>0) {
            // write result in array at appropriate position
            $ImageView[$counter++] = $AutomaticallyOpenShow.$curimg;
        }

}   

html代码如下:

<img src="<?php echo $ImageView[0]; ?>" width="500" height="500" />

答案 2 :(得分:0)

$AutomaticallyOpenShow = $AutomaticallyOpen."/";
$images = scandir($AutomaticallyOpen,0);
$counter = 1;
foreach($images as $curimg) {
  if (preg_match('/^.*\.[jpeg]{3,4}$/i', $curimg)) {

    if($counter >= 1 && $counter <= 4){
      $varName = 'ImageView_'.$counter;
      $$varName = $AutomaticallyOpenShow.$curimg;
    }

    $counter++;
  }
}