PDA

View Full Version : sorting flat-file db entries


Razorwyre
08-15-2002, 04:34 PM
Here's the deal: I've got a flat-file (text file) database that stores a simple list of items, as such:

Category|Title|Description|Date

(Date is in the format: YYYYMMDD -- so it should be easy to sort numerically)

Each line in the file is a new entry. What I'm trying to do is write a function that will read all the lines from the file, sort them by date with the newest at the top, and write back a new file with everything in a nice, sorted order.

I can read the file and use split() to get each of the four pieces of data from each row. That's easy enough. My difficulty is in figuring out how best to do the sort. If this were a mysql db, it'd be easy to just sort the data with mysql before pulling it out... but since it's a text file db, it requires more work... (I was thinking of trying a multiarray and using the multisort array function, but I'm not sure even how to go about that or if it's the easiest solution...)

anyone able to help?
thanks in advance!

-raz

stuntboy
08-16-2002, 07:30 PM
Is there any chance of putting it as:

Date|Category|Title|Description

I had once written a function to do just what you want, but I cant find it lol.

firepages
08-17-2002, 01:31 AM
3 cheers for array_reverse()


<?
$yaks=file('data.txt');
foreach($yaks as $line){
$bits=explode('|',$line);
$bits=array_reverse($bits);
$temp[]=$bits;
}

sort($temp);

$fp=fopen('data.txt','w');
while(list($key,$var)=each($temp)){
$bits=array_reverse($var);
$bits=implode('|',$bits);
fputs($fp,trim($bits)."\n");
}
fclose($fp);
?>

stuntboy
08-17-2002, 02:00 AM
Cool :D never thought of that one