Hey guys
I was wondering if anyone could tell me how I would use the usort(); tag correctly, I don't quite undestand the one given in php.net
The situation is that I have a text file with names in it each name is assigned ot a new line and I would like to be able to pront the names in alphabetical order. I seem to have to put the names into an array but was wondering how I would go about this.
Thanks
Andy
Sorting a list in a text file into alphabetical order
Moderator: General Moderators
-
andylyon87
- Forum Contributor
- Posts: 168
- Joined: Sat Jan 31, 2004 5:31 am
- Location: Dundee
First read the file into a string using file_get_contents(). Then change the string into an array using explode(). You'll have to find out what character is being used for the line break. I think someone said it was \are for notepad. Unix/Linux it's \n. Then use asort() to alphabetize it.
Hope this helps.
Hope this helps.
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Actually you should use file() as it already converts each line of a file into a new array element.
Also you want sort() in this case, not usort()
Code: Select all
$file = file('usernames.txt');
sort($file);
print_r($file);
Last edited by John Cartwright on Mon Jun 13, 2005 6:54 am, edited 1 time in total.
-
andylyon87
- Forum Contributor
- Posts: 168
- Joined: Sat Jan 31, 2004 5:31 am
- Location: Dundee
I have a problem with this as I need to have each of the usernames in the list linked to a specific area on the site, so for this i have used n explode. Shown below.
After reading the ideas I have tried to sort() the file by adding the following below the fclose($pointer); -
This didnt work so I tried -
in the same place this returned a number 1.
What would I need to do
Code: Select all
<?
print("<center><H2>Userlist</H2>");
$file="users/list.txt"; //file used
$pointer=fopen($file,"r"); //opens file
$lines_array=file($file);
fclose($pointer);
for($k=0; $k<count($lines_array); $k++) {
$line_array=explode("\n",$lines_array[$k]);
$names=$line_array[0];
$name=ucfirst($names);
$totalphotos = file_get_contents("users/$names/uploads.txt"); //gets a number form a txt file
print("<P><A href=users/$names target=_blank>$name's Photos</A> - [$totalphotos]"); // prints the username and the number from the txt file
}
?>Code: Select all
$lines_array=sort($pointer);Code: Select all
$sort=sort($lines_array);
$lines_array=print_r($sort);What would I need to do
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact: