Vanilla 1 is no longer supported or maintained. If you need a copy, you can get it here.
HackerOne users: Testing against this community violates our program's Terms of Service and will result in your bounty being denied.

Reverse List

edited April 2007 in Vanilla 1.0 Help
I am writing an extension where people post interesting links for all to see, it seems to be working OK.

My problem is that new links are added to the bottom of the list (it uses a flat text file) so the old links are always at the top.

Is there a way (PHP) that I can reverse the entries so the new ones are at the top?

This is my current code (no laughing please)...
$link_file="links.txt"; $write = "<a href=\"$url\">$name</a> | $desc<br>\n"; $fp=fopen($link_file, "a"); fwrite($fp, $write); fclose($fp);

Posted: Tuesday, 10 April 2007 at 12:17PM

Comments

  • I did a google and found 2 things which I then went into my php reference to learn more about. After you open the file, you should be able to use a fseek(SEEK_END) to get to the end of the file. Then do a fseek(-1) to get to the beginning of the last record and fread() it. Then fseek(-1) and so one walking back thru the file.

    This method does it more elegantly.
  • Thanks jimw, I searched hi and lo, obviously your Googling skills are better than mine.
    Test it here if you like.

    Posted: Tuesday, 10 April 2007 at 1:59PM

  • edited April 2007
    php newbie question: isn't it easier to just read the whole file one record at a time into an array, reorder the array, then output it?
  • Another php newbie here!
    The method Jim suggested worked first time with no modification, I'm happy.

    Posted: Tuesday, 10 April 2007 at 4:44PM

  • Reading the file into an array is also an option and then reverse sorting it or reading thur it backwards. However, with really large files, I think the reverse read technique is more efficient from what I understand. Also, if you just need to pick off the most recent entries, say a certain number, then the reverse read is more efficient.
  • you should really use a table tho eh?
  • @Mr Do: The use of a database table is not always the most efficient way to work with data.
  • MarkMark Vanilla Staff
    What icouto said. Use php's file method to read every line of the file into an array. Then reverse it. Then add a new item. Then reverse again. Then save.
  • Exemple: to read the file:echo implode('', array_reverse(file('links.txt')));
  • MarkMark Vanilla Staff
    I'd just go:
    $File = 'links.txt'; $Lines = file($File); if (is_array($Lines)) { $ReversedLines = array_reverse($Lines); $ReversedLines[] = "my new value"; $Lines = array_reverse($ReversedLines); $ConcatentatedLines = implode('', $Lines); $FilePointer = fopen($File, "a"); fwrite($FilePointer, $ConcatenatedLines); fclose($FilePointer); }

    That's untested code ... but it's something along those lines...
This discussion has been closed.