Well, one: get a database,. two: I assume the second field in each record is only the first letter of a persons surname (it looks like that, and you didn't specify anything else 😉..
I'm just going to write out of my head some sort of sloppy code that will (hopefully) at least give you an idea on how to do this. The reason I mentioned the second field, is that there is no point using it. If you sort by surname, its easier to break up 'per-first-letter' after we sorted it. (Otherwise the array would need to be sorted on both the fields 'first letter' and 'surname', I'd only sort it by surname.)
$lines = array();
$sortField = 3;
$count = 0;
$fp = fopen("file.txt", "r");
while (!feof($fp)) {
$oneLine = fgets($fp, 4096);
$exp = explode("|", $oneLine);
$lines[$exp[$sortField].$count++] = $exp;
}
fclose($fp);
/*
This would make an array $lines where each entry contains an array of the data stored in one record of your text-file.
Note that the count++ part of the array key is to avoid overwriting data if two people have the same surname.
The correct way to do this, is probably to write your own sort function and use usort() to sort a multi-dimensional array, but I just couldn't be bothered.
*/
ksort($lines); / sort array by key /
$breakBy = ""; / Current char we're in /
$breakField = $sortField; / What field of $val to break by (hint; the one you sorted by.. but you could choose something else..) /
foreach ($lines AS $key => $val) {
$firstChar = substr($val[$breakField], 0, 1); / get first char of field we're breaking from /
if ($firstChar != $breakBy) { / if different from current .. /
$breakBy = $firstChar; / set new current /
print "$firstChar:<br>"; / print new /
}
foreach ($val AS $key2 => $val2) / print data for current /
print "$val2 ";
print "<br>"; / .. and line break 🙂 /
}