Tricky explode(), help please!

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hello Everyone,

I have a situation that I just cannot wrap my head around.  I would
appreciate any ideas or suggestions.

I am trying to parse and load a tab delimited file into a mysql
database.  The file is generated by a scientific instrument.  One file
contains the records of several people.  Each person's information is
in 3 consecutive lines of the file.

A simplified demonstration:

id | test | result
1 | test1 | 50
   | test 2 | 55
   | test 3 | 60
2 | test 1 | 10
   | test 2 | 15
   | test 3 | 20

When I load this information into the database, it should have this
id | test 1 | test 2 | test 3
1  |   50    |  55    |  60
2  |   10    |  15    |  20

I'm okay with setting up the database, that's no problem.

I am however rather new to PHP and although I know I have to use the
explode() function to break this array down into its parts, I'm not
exactly sure how.  Specifically, one file could contain the records of
up to 20 people, and I am not sure how I can loop through this file
(loaded into an array) in order to capture all of this info.

I hope I've given enough information to make sense.  Again, any ideas,
examples or suggestions would be appreciated.


Re: Tricky explode(), help please! wrote:
Quoted text here. Click to load it

Unless you know for sure that you will ALWAYS only have 3 tests then  
your table design is flawed.  If there can be more or less tests then
you want to use something like:


It would take much less programming to insert this kind of data and then  
you can use this cool "pivot table" example to retrieve the data- which  
is identical to  what you are trying to do...


processing the array - NOT REAL SYNTAX - that is left to the programmer.

    read file into array
        process array
        if ID is not emtpy or is null or = ''
             (or whatever charaters are in the first position)
            excute insert statement or write to an output
            and load output file when all rows have been

        goto loopstart

Re: Tricky explode(), help please! wrote:
Quoted text here. Click to load it

$data = file('c:\data0602_001.txt');
$flip = array();
$i = 0;
foreach ( $data as $line )
    $a = explode("\t", rtrim($line));
    if ( $a[0] ) $i = $a[0];
    switch ( $a[1] )
        case 'test 1': $j = 1; break;
        case 'test 2': $j = 2; break;
        case 'test 3': $j = 3; break;
        default: $j = 99;
    $flip[$i][$j] = $a[2];
$flat = array();
foreach ( $flip as $k => $v )
    $v[0] = $k;
    $flat[] = implode("\t", $v);

$fh = fopen('c:\data0602\new_20_001.txt', 'wb');
fwrite($fh, implode("\r\n", $flat)."\r\n");

E. Dronkert

Site Timeline