Page 1 of 1
sort() problems
Posted: Mon Aug 18, 2003 12:01 pm
by banpro
Hi, I'm trying to use sort to alphabetize a listing of names but I'm having trouble with the functions. I need to open the list, read it into an array, sort it and then rewrite the list in alphabetic order. Here's what I have but it isn't working as expected.
Code: Select all
//Alpha sort the directory
$fpp = fopen("listing.php", 'r');
while(!feof($fpp))
{
$line = fgets($fpp, 1024);
}
fclose($fpp);
sort($line);
reset($line);
// Rewrite the directory
$ffpp = fopen("listing.php", 'w');
fwrite($ffpp, "$line");
fclose($ffpp);
Any ideas or suggestions are most welcomed and appreciated.
Thanks in advance,
Scott
Posted: Mon Aug 18, 2003 12:09 pm
by JayBird
not working as expected?
What is happening?
Posted: Mon Aug 18, 2003 12:19 pm
by banpro
It hangs on the sort() & resort() commands with the folowing errors:
Warning: sort() expects parameter 1 to be array
Warning: reset(): Passed variable is not an array or object
Thanks,
Scott
Posted: Mon Aug 18, 2003 12:25 pm
by JayBird
this line isn't creating an array
it will just equal the last line of the file you are reading from.
Try this
Code: Select all
$x = 0;
while(!feof($fpp)) {
$line[$x] = fgets($fpp, 1024);
$x++
}
Mark
Posted: Mon Aug 18, 2003 12:36 pm
by banpro
Mark, thanks, that stops the errors. However, now the output back to the file after being sorted isn't the directory listing in alphabetic order, but rather just the word "Array"?
Here's the updated code now:
Code: Select all
//Alpha sort the directory
$fpp = fopen("listing.php", 'r');
$x = 0;
while(!feof($fpp)) {
$lineї$x] = fgets($fpp, 1024);
$x++;
}
fclose($fpp);
sort($line);
reset($line);
// Rewrite the directory
$ffpp = fopen("listing.php", 'w');
fwrite($ffpp, "$line");
fclose($ffpp);
Thanks again for the help,
Scott
Posted: Mon Aug 18, 2003 12:40 pm
by JayBird
Try this mate
Code: Select all
//Alpha sort the directory
$fpp = fopen("listing.php", 'r');
$x = 0;
while(!feof($fpp)) {
$line[$x] = fgets($fpp, 1024);
$x++;
}
fclose($fpp);
sort($line);
reset($line);
// Rewrite the directory
$ffpp = fopen("listing.php", 'w');
foreach($line as $new_line) { // itterate through the array and write each line
fwrite($ffpp, "$new_line\n"); // write the line and insert a line break
}
fclose($ffpp);
Mark
Posted: Mon Aug 18, 2003 12:46 pm
by banpro
Perfect! Mark, you're a life-saver.
I really need to re-RTM on arrays this evening.
Thanks for the help,
Scott