开发者

Sorting a list in PHP

开发者 https://www.devze.com 2023-01-01 18:30 出处:网络
Alright, so I\'ve just (almost) finished my first little php script. Basically all it does is handling forms. It writes whatever the user put in to the fields of the form to a text file, then I includ

Alright, so I've just (almost) finished my first little php script. Basically all it does is handling forms. It writes whatever the user put in to the fields of the form to a text file, then I include that text file in the index of the little page I have set up.

So, currently it writes to the beginning of the text file (but doesn't overwrite previous data). But, several users wants this list to be alphabetically sorted instead. So what I want to do is make whatever they submit fall into the list in alphabetical order.

The thing here is also that all I use in the text file are divs. The list is basically 'divided' into 3 parts. 'Title', 'Link', and 'Poster'. All I have done is positioned them with css.

So, can I sort this list (the titles, in this case) alphabetically and still have the 'link' 开发者_运维技巧and 'poster' information assigned the way they already are, but just with the titles sorted?

It don't use databases at all on my site, so there is no database handling at all used in this script (mainly because I'm not experienced at all in this).


I would also suggest storing the data in the file as either XML or JSON. PHP can sort the records easily and the sorting will be preserved in the file when the data is read back in.

For example

file_put_contents("/tmp/datafile",json_encode($recordset));

and when reading the file back in

$recordset = json_decode(file_get_contents("/tmp/datafile"));

edit

but seriously if you have customers and are charging them for your experience and time, use a database, there are many out there (a few mentioned already)

  • MySQL
  • sqlite
  • PostgreSQL
  • Oracle
  • MSSQL


If you really don't want to use a database, even a one-file database (such as sqlite), you can group the three fields using a separator such as _ and sort this single-field list


If this is a small project for some friends or something and the file shouldn't ever have more than maybe a few hundred lines, the functions you're looking for are "file" and "usort".

If you make sure each row is on its' own line, you can load the lines into an array with "file". You can sort the array using a function to compare items with the "usort" function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号