Jump to content

Archived

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

xbase

sort tab delimited array from file

Recommended Posts

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:
[code=php:0]
<? 

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>";

?>
[/code]

Share this post


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

Share this post


Link to post
Share on other sites
something like..

[code]<?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]
    [/code]

Share this post


Link to post
Share on other sites

×

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.