Brod Wilkinson Brod Wilkinson - 1 month ago 12
PHP Question

Sort text file in table alphabetically

I'm having trouble sorting a text file and categorizing each line by the first letter.. here's where I'm at..

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 output

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


desired output

A B L O
Apple Banana Lemon Orange
Apricot


So I understand why its currently outputting double the original text file as I'm echoing it twice but I can't figure out how I can tell it I only want lines starting with A under A and B under B etc..

Answer

You can try:

$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>
Comments