回显循环数组,奇怪的行为,php

echo out loop array, strange behaviour, php

我正在使用我在网上找到的这段代码来输出链接。

https://2buntu.com/articles/1301/php-script-to-dynamically-generate-links-to-the-files-present-in-current-directory/

    <?php
    $dir_open = opendir('.');

    while(false !== ($filename = readdir($dir_open))){
        if($filename != "." && $filename != ".."){
            $link = "<a href='./$filename'> $filename </a><br />";
            echo $link;
        }
    }

    closedir($dir_open);
    ?>

现在我想按字母顺序排序,所以我放入一个数组,排序并输出。但是我得到了一些奇怪的重复输出,结果比应该的多 100 倍。这是怎么回事?

<?php
$dir_open = opendir('./myfolder/');

while(false !== ($filename = readdir($dir_open))){
    if($filename != "." && $filename != ".."){
        $array[] = "<a href='./myfolder/'> $filename </a><br />";
        sort($array, SORT_NATURAL);
        foreach ($array as $key => $val) {
            echo $val;
        }
    }
}

closedir($dir_open);
?>

完整代码

<?php
$dir_open = opendir('./suburblist/');

while(false !== ($filename = readdir($dir_open))){

    if($filename != "." && $filename != ".." && $filename != (preg_match('/\.html$/i', $filename))) {

        $domfilename = preg_replace('/\.[^.\s]{3,4}$/', '', $filename);        
        $domfilename = str_replace("-", " ", "$domfilename");
        $domfilename = ucwords("$domfilename");   
        $array[] = $domfilename;
    }
}

sort($array, SORT_NATURAL);

foreach ($array as $val) {

    echo "<a href='/suburblist/$filename'>$val </a>"; 
}

closedir($dir_open);
?>

您需要做的是:

  • 获取数组中的所有文件名
  • 排序数组一次
  • 输出排序数组一次

// get all filenames in array
while (false !== ($filename = readdir($dir_open))){
    if($filename != "." && $filename != ".."){
        $array[] = $filename;
    }
}

// sort array
sort($array, SORT_NATURAL);

// output values from array
foreach ($array as $val) {
    echo "<a href='./myfolder/'> $val </a><br />";
}

两个变量更新:

// get all filenames in array
while (false !== ($filename = readdir($dir_open))){
    if($filename != "." && $filename != ".."){
        $array[] = ['name' => $filename, 'link' => 'another value'];
    }
}

// sort array with custom function, as your array is multidimensional now:
usort(
    $array, 
    function ($a, $b) { return strnatcmp($a['name'], $b['name']); }
);

// output values from array
foreach ($array as $val) {
    echo "<a href='./myfolder/" . $val['link'] . "'>" . $val['name'] . "</a><br />";
}