以特定的堆栈顺序编写img标签

时间:2014-08-09 19:14:10

标签: php

我们说imgT文件夹有五张图片 - 从01.jpg05.jpg

function givemeG($path) {
$files = glob($path . '*.jpg');
$cs=" class=\"act\"";
foreach($files as $img) { 
    echo "<img" . $cs . " src=" . "\"" . $img . "\"" . " alt=\"img\">";
    $cs="";
    echo "\n";
}
}
$path = "imgT/";
givemeG($path);

这将产生以下结果:

<img class="act" src="imgT/01.jpg" alt="img">
<img src="imgT/02.jpg" alt="img">
<img src="imgT/03.jpg" alt="img">
<img src="imgT/04.jpg" alt="img">
<img src="imgT/05.jpg" alt="img">

有没有办法获得以下结果:

<img class="act" src="imgT/01.jpg" alt="img">  // lowest number (01)
<img src="imgT/05.jpg" alt="img">  //  highest number (05)
<img src="imgT/02.jpg" alt="img">  // next lowest (02)
<img src="imgT/04.jpg" alt="img">  // next highest (04)
<img src="imgT/03.jpg" alt="img">  // next lowest (03)
... etc following the same pattern if there is more images.

我希望它清楚 - 从想象的数字数组的外部(最低和最高)到内部(下一个最低和次高)。

1 个答案:

答案 0 :(得分:1)

我相信这应该做你想做的事:(on codepad)

<?php
$arr = array(1,2,3,4,5);
$len = count($arr);
$even = $len%2==0; //Are there an even number of elements in the array?
$middle = $even ? ceil($len/2) : floor($len/2); //Gets point at which we stop
foreach($arr as $key => $value)
{
    if($key==$middle && $even) break; //If it's an even counted array, and we've reached our 'middle' stop processing
    echo $value;
    echo "\r\n";
    if($key < $middle) //If we're not at the middle yet, find the appropriate element from the end of the array
    {
        echo $arr[$len-($key+1)];
        echo "\r\n";
    }
    else if($key==$middle) break;
}

它基本上只是一个正常的循环,但是对于每一个,它使得元素距离末尾的距离与从头开始的距离相同。

如果我没有让方法足够清楚,请告诉我。