按字母顺序对表中的文本文件排序


Sort text file in table alphabetically

我在整理文本文件和按首字母对每行进行分类时遇到了麻烦。这就是我现在的处境

list.txt

Apple
Orange
Apricot
Banana
Lemon

categorize.php

<?php
$fname = file("list.txt");
sort($fname);
for($i=0; $i<count($fname); $i++)
{
$states = explode(",", $fname[$i]);
?><table>
<th>A</th><th>B</th><th>L</th><th>O</th>
<tr><td><?php echo [A],$states[0];?></td>
<td><?php echo [B],$states[0];?></td>
<td><?php echo [L],$states[0];?></td>
<td><?php echo [O],$states[0];?></td></tr>
</table>
<?php
}
?>

categorize.php

输出
A B L O
Apple Apple Apple Apple
A B L O
Apricot Apricot Apricot Apricot
A B L O
Banana Banana Banana Banana
A B L O
Lemon Lemon Lemon Lemon
A B L O
Orange Orange Orange Orange 

期望输出值

   A     B      L     O
 Apple Banana Lemon Orange
Apricot

所以我理解为什么它目前输出的原始文本文件的两倍,因为我回显它两次,但我不知道我怎么能告诉它,我只希望行开始与A下A和B下B等。

您可以尝试:

$fname = file("list.txt");
sort($fname);
$category = array();
foreach($fname as $var) {
    $category[strtoupper(substr($var, 0, 1))][] = $var;
}
printf("<table>");
printf("<th>");
foreach(array_keys($category) as $v) {
    printf("<td>%s</td>", $v);
}
printf("</th>");
array_unshift($category, null);
foreach(call_user_func_array("array_map", $category) as $v) {
    printf("<tr>");
    foreach($v as $d) {
        printf("<td>%s</td>", $d);
    }
    printf("</tr>");
}
printf("</table>");

HTML输出
<table>
    <th>
    <td>A</td>
    <td>B</td>
    <td>L</td>
    <td>O</td>
    </th>
    <tr>
        <td>Apple</td>
        <td>Banana</td>
        <td>Lemon</td>
        <td>Orange</td>
    </tr>
    <tr>
        <td>Apricot</td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>