Jump to content


Photo

sort tab delimited array from file


  • Please log in to reply
2 replies to this topic

#1 xbase

xbase
  • New Members
  • Pip
  • Newbie
  • 8 posts

Posted 13 September 2006 - 03:11 AM

Ok i'm reading from a file that likes look so:

GATE The Gate voodoo://chat.fearlab.net=GATE 0 250 0 GEN
POTTER harry potter net voodoo://chat.fearlab.net=POTTER 0 30 0 GEN
SYCOSI Syc0sis voodoo://chat.fearlab.net=SYCOSI 1 30 0 GEN
HANG H a N g O uT voodoo://chat.fearlab.net=HANG 0 30 0 GEN
GUYZ Syc0 Guyz voodoo://chat.fearlab.net=GUYZ 0 30 0 MEN
SOUTH Southern Comfort Music Room voodoo://chat.fearlab.net=SOUTH 0 30 0 MUS

its tab delimeted which isnt a problem, but when I do the for each statement , how can I make it sore by lets say $array[3] but throughout the entire file?

Here is my coding:
<?  

function row_color($k){
    $bg1 = "#909090"; // color one    
    $bg2 = "#c0c0c0"; // color two

    if ( $k%2 ) {
        return $bg1;
    } else {
        return $bg2;
    }
} 

$readfile = file("../../voodoo/rooms.txt");

// create a loop that will read all elements of the array and print out
// each field of the tab-delimited text file
echo "<table border=\"0\" cellspacing=\"0\" cellpadding=\"2\" width=\"650\" align=\"center\">
<tr>
<td width=\"30\" class=\"header\">Number </td>
<td width=\"300\" class=\"header\">Room Name</td>
<td width=\"20\" class=\"header\">Users</td>
</tr>";

for ($k=0; $k<=count($readfile)-1; $k++) {
	
    $fields = split("\t",$readfile[$k]);	
    
	echo "
    <tr>
    <td width=\"30\" class=\"info\" bgcolor=".row_color($k).">$k</td>
    <td width=\"300\" class=\"info\" bgcolor=".row_color($k)."><a href=$fields[2]>$fields[1]</a></td>
    <td width=\"20\" class=\"info\" bgcolor=".row_color($k).">$fields[3]</td>
    </tr>
    ";

    
}
echo "
    <tr>
    <td colspan=3 class=\"footer\" align=right>Total Rooms: $k</td>
    </tr>
    </table>";

?>


#2 yaba

yaba
  • Members
  • PipPip
  • Member
  • 27 posts

Posted 13 September 2006 - 04:00 AM

I'm not sure you can do this once you call the split() function. What I would do is put the field I want to sort by as the first thing for every line in my file and then sort the $readfile array using one of the... array sort functions (sort, ksort, asort etc), before splitting...

#3 Jenk

Jenk
  • Members
  • PipPipPip
  • Advanced Member
  • 778 posts

Posted 13 September 2006 - 09:19 AM

something like..

<?php

$file = file('/path/to/file.csv');

foreach ($file as $line)
{
    foreach (explode("\t", $line) as $num => $col)
    {
        echo '<p>' . htmlentities($col) . '=' . htmlentities($num) . '</p>';
    }
}

?>
    [/code]




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users