0

我有 2 组代码,它们都可以独立工作,但我需要将它们结合起来,并且无法做到。

最终结果应该是逐行显示一个文本文件,数组 # 按字母顺序排列(因此数组编号应该显示在每行的末尾)。

第一段代码

<?php
$filename="users.txt"; 
$lines = array();
$file = fopen($filename, "r");

while(!feof($file)) { 
    $lines[] = fgets($file,4096);
} 

natcasesort($lines);
$text = implode("<br />", $lines);
print_r($text);

fclose ($file); 
?>

第二段代码

<?php 
 $lines = file('users.txt'); 
 foreach ($lines as $line_num => $line) 
{ 
 print "<font color=red>Line #{$line_num}</font> : " . $line . "<br />\n"; 
 }
 ?> 
4

1 回答 1

0

有两种简单的方法可以做到这一点。这个仅适用于 PHP >= 5.4.0:

$lines = file('users.txt');
asort($lines, SORT_NATURAL | SORT_FLAG_CASE); // natcasesort that preserves keys!

foreach ($lines as $num => $line) { 
    printf("%s (line #%d)<br>", $line, $num);
}

如果使用较早的版本,您可以使用uasortand达到相同的效果strnatcasecmp

$lines = file('users.txt');
uasort($lines, 'strnatcasecmp'); // natcasesort that preserves keys

// the loop is the same

看到它在行动

In both case the idea is to use a sort function that maintains index association, so that after the lines are sorted they remain indexed by their original key (which is the line number in the file). Both usort and uasort do this; uasort allows you to specify the sort comparison function yourself while usort only allows a few built-in options (which do not include natural sorting in PHP < 5.4).

As an aside: please do not use the <font> tag ever again.

于 2012-04-10T14:48:06.990 回答