Jump to content

sorting a textfile database


php_joe

Recommended Posts

Hi,

If I have a database stored on a text file that looks like this:

animal|dog|cat|mouse
eats|cats|mice|grass
poops in|my yard|my house|my cereal

I can sort the table by the first column like this:
[code]<?
$data = file($database);
sort($data);
?>[/code]

Is there an easy way to sort the database by the second or third column?

Thanks!

Joe
Link to comment
https://forums.phpfreaks.com/topic/26593-sorting-a-textfile-database/
Share on other sites

I'm just trying to make a table that I can sort by any column. I don't want to change the information in the lines.

I've been playing around with it a bit and I [i]could[/i] reorder the lines
[code]<?
foreach($data as $key => $value){
list($one, $two, $three, $four) = explode("|", $value);
$array = array($four, $three, $two, $one);
$data[$key] = implode("|", $array);
}
$table = implode("\n", $data);
sort($data);
?>[/code]
But it seemed a bit cumbersom and I was hoping that there was a better way.

Joe
Here´s a solution, use a [url=http://www.php.net/usort]usort()[/url] and a callback function. Then split the string by the column you want to sort on.

ex:
[code]<?php

function do_sort($a, $b) {

// Sort by the second column
list( , $test_a) = explode('|', $a);
list( , $test_b) = explode('|', $b);

  if ($test_a == $test_b) return 0;
 
  return ($test_a < $test_b) ? -1 : +1;

}


$array[] = array("animal|dog|cat|mouse");
$array[] = array("eats|cats|mice|grass");
$array[] = array("lives in|my yard|my house|my attic");


usort($array, "do_sort");
print_r($array);

?>[/code]
[quote author=Nicklas link=topic=114288.msg465084#msg465084 date=1163018882]
If you want to sort on the second column, then you need to make sure that all lines have atleast 2 columns, that´s all you need to know. Number of lines doesnt matter.
[/quote]

Oh yes, I see.

Thank you very much! :)

Joe

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.