我无法对文本文件进行排序,并按照第一个字母对每一行进行分类..这就是我所在的位置..
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和B下以A开头的行等等。
答案 0 :(得分:-1)
您可以尝试:
$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 OUTPUT
<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>