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
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
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

[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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.