Jump to content

Retrieve data from text file...stuck...


lindm

Recommended Posts

I have a text file (accounting information) which contains a lot of information and some of this information (numbers) I want to retreive (import to a php script) and be able to use some figures in calucations etc. Here is a piece of the text which shows the build up of the information I want to use:

 

----text file excerpt----

 

#IB 0 2099 -226930.95

#IB 0 2510 -81219.00

#UB 0 2641 1114.28

#UB 0 2645 6978.00

#UB -1 2890 -43750.55

#RES 0 5800 46239.60

#RES -1 5900 574.92

#RES 0 5900 6402.63

 

----end----

The identifier is the column containing 2099, 2510, 2641 etc. So for example in a php file a function (extract for example) will open the text file and extract the number to the right based on the identifier column. Php example

 

(extract(2099) + extraxt(2641)) will result in: -225816,67

 

Any help much appreciated.

Link to comment
Share on other sites

Something like this:

$contents = file('test.txt');

foreach($contents as $line_id => $line_value)
{
    list(, , $id, $num) = explode('   ', $line_value);

    $number[$id] = $num;
}

echo $number[2099] + $number[2641];

 

However with that code, it'll only store the last number for the following:

#RES   -1   5900   574.92
#RES   0   5900   6402.63

in the $numbers variable, it wont store both values for 5900

Link to comment
Share on other sites

I believe the information is tab delimeted...does that facilitate things? I also now understand what -1 and 0 stands for...-1 is the value of previous year...this complicates it a bit more...I therefore now need to extract a number based on at least three conditions:

 

1. the line beginning with #IB, #UB or #RES

2. if the following controller i s0 or -1

3. the four digit following identifier (1220, 1299 etc)

 

So a function with three variables perhaps? getdata($var1,$var2,$var3)

Perhaps there is an easier way? I am just a beginner...

Link to comment
Share on other sites

Ok here is my code so far for fgets...need some help to complete it...how do I get a certain data?

 

<?PHP

$file_handle = fopen("sie.txt", "rb");

while (!feof($file_handle) ) {

$line_of_text = fgets($file_handle);
$parts = explode('\t', $line_of_text);

print $parts[0] . $parts[1]. "<BR>";
}

fclose($file_handle);

?>

 

Link to comment
Share on other sites

Sorry, will be a bit clearer...how do I for instance get the number 246892.00 from the text file below?

 

 

---file.txt-----

#IB 0 2510 -81219.00

#IB 0 2640 495.37

#IB 0 2890 -43750.55

#IB 0 2990 -2300.00

#UB -1 1229 -4700.00

#UB 0 1229 -4700.00

#UB -1 1250 14100.00

#UB 0 1250 14100.00

#UB -1 1410 20000.00

#UB 0 1410 20000.00

#UB -1 1510 246892.00

 

Link to comment
Share on other sites

Thanks for your paitience  ::)

 

Is there some code like for sql? For instance get $row[2] where $row[1] ==1510?

 

I want to be able to initiate a php function give it some variable ($row[1] == 1510 as an example) and it will return 246892.00.

Link to comment
Share on other sites

From what I have a read it looks like the following should do the trick:

$contents = file('file.txt');

foreach($contents as $line_value)
{
    list($cat, $int, $id, $num) = explode('   ', $line_value);

    $cat = str_replace('#', '', $cat);

    $number[$cat][$int][$id] = trim($num);
}

//echo '<pre>' . print_r($number, true) . '</pre>';


echo $number['IB'][0][2510]; // returns -81219.00

// similarly $number['UB'][-1][1229]; will return 14100.00

 

These numbers are based on the numbers in your post here.

Link to comment
Share on other sites

Looks like what I am after but the script (below) doesn't work. The php script and the file.txt in the same directory and I excuted the script...what am I doing wrong?

<?PHP


$contents = file('file.txt');

foreach($contents as $line_value)
{
    list($cat, $int, $id, $num) = explode('   ', $line_value);

    $cat = str_replace('#', '', $cat);

    $number[$cat][$int][$id] = trim($num);
}

//echo '<pre>' . print_r($number, true) . '</pre>';


echo $number['IB'][0][2510]; // returns -81219.00

// similarly $number['UB'][-1][1229]; will return 14100.00

?>

 

 

Link to comment
Share on other sites

What is the space between each 'column'. Is it a tab? If its change this line:

list($cat, $int, $id, $num) = explode('   ', $line_value);

To this:

list($cat, $int, $id, $num) = explode("\t", $line_value);

I thought it was three spaces as this is what you have been posting with your examples for file.txt

Link to comment
Share on other sites

It is because that code puts "UB" into the same key location multiple times, overwriting the previous value. If you only are going to use the id (ie. 2510) to find the number, you only need one dimension for your array. You could change that code to:

$number = array();
foreach($contents as $line_value)
{
   $values = explode('\t', $line_value);
   $number = array_flip($number);
   $number[] = $values[2];
   $number = array_flip($number);
   $number[$values[2]] = str_replace('#', '', $values[3]);
}

 

That should put all the ids in the keys and all the numbers in the respective values. There might be a better way to add them into the array, but I can only remember how to add values only, not keys and values, but that works for doing it.

Link to comment
Share on other sites

It is because that code puts "UB" into the same key location multiple times, overwriting the previous value. If you only are going to use the id (ie. 2510) to find the number, you only need one dimension for your array. You could change that code to:

$number = array();
foreach($contents as $line_value)
{
    $values = explode('\t', $line_value);
    $number = array_flip($number);
    $number[] = $values[2];
    $number = array_flip($number);
    $number[$values[2]] = str_replace('#', '', $values[3]);
}

 

That should put all the ids in the keys and all the numbers in the respective values. There might be a better way to add them into the array, but I can only remember how to add values only, not keys and values, but that works for doing it.

My code generates the following array, it wont 'overwrite' existing keys/values:

Array
(
    [iB] => Array
        (
            [0] => Array
                (
                    [2510] => -81219.00
                    [2640] => 495.37
                    [2890] => -43750.55
                    [2990] => -2300.00
                )

        )

    [uB] => Array
        (
            [-1] => Array
                (
                    [1229] => -4700.00
                    [1250] => 14100.00
                    [1410] => 20000.00
                    [1514] => 246892.00
                )

            [0] => Array
                (
                    [1229] => -4700.00
                    [1250] => 14100.00
                    [1410] => 20000.00
                )

        )

)

There is not a problem with my code. Its to do with how file.txt is formated

Link to comment
Share on other sites

I need several identifiers and it was a tab so this is the code currently working. Thanks all!!

Quick questions. Is this code ok from a memory perspective? Some of the text files can contain a lot of info. What is this part of the code? :

//echo '<pre>' . print_r($number, true) . '</pre>';

 

 

Current code:

<?PHP


$contents = file('file.txt');

foreach($contents as $line_value)
{

list($cat, $int, $id, $num) = explode("\t", $line_value);

    $cat = str_replace('#', '', $cat);

    $number[$cat][$int][$id] = trim($num);
}

//echo '<pre>' . print_r($number, true) . '</pre>';


echo $number['UB'][-1][1650]*2;// returns -81219.00

// similarly $number['UB'][-1][1229]; will return 14100.00

?>

 

 

Link to comment
Share on other sites

What is this part of the code? :

//echo '<pre>' . print_r($number, true) . '</pre>';

That line is commented out. If you uncomment it it'll echo out the contents of the $number variable, which will display how the array is formatted.

 

Not sure what you mean by this question:

Is this code ok from a memory perspective? Some of the text files can contain a lot of info

 

Link to comment
Share on other sites

The last question is if the script is effective in executing, cache etc?

 

What is this part of the code? :

//echo '<pre>' . print_r($number, true) . '</pre>';

That line is commented out. If you uncomment it it'll echo out the contents of the $number variable, which will display how the array is formatted.

 

Not sure what you mean by this question:

Is this code ok from a memory perspective? Some of the text files can contain a lot of info

 

Link to comment
Share on other sites

wildteen88,

 

Short followup question. Is there an easy way to create sums? FOr instance say I want to create a sum of

 

$number['UB'][-1][1600] + $number['UB'][-1][1601] + $number['UB'][-1][1603] + up to $number['UB'][-1][1650];

 

How would I do this in an easy way?

 

Thanks

Link to comment
Share on other sites

Best creating a function which you pass the number group (UB and -1) and the range (1600 and 1650) which will total up the range from UB -1 1600 to UB -1 1650

function calculate_range($cat, $bool, $range_min, $range_max)
{
    global $number;

    $total = 0;

    for($i = $range_min; $i <= $range_max; $i++)
    {
        if(isset($number[$cat][$bool][$i]))
        {
            $total += $number[$cat][$bool][$i];
        }
    }

    return $total;
}
// calculate range UB -1 1600 tp UB -1 1650
echo calculate_range('UB', -1, 1600, 1650);

Link to comment
Share on other sites

  • 2 months later...

This is follow up for you wildteen. Hope you remember this issue, you helped me create an import script with two seperate parts, one for a certain number and one for a range as below:

 

Part one

$contents = file($_FILES['userfile']['name']); 
foreach($contents as $line_value)
{
list($cat, $int, $id, $num) = explode("\t", $line_value);

    $cat = str_replace('#', '', $cat);

    $number[$cat][$int][$id] = trim($num);
}

 

Part two

function calculate_range($cat, $bool, $range_min, $range_max)
{
    global $number;

    $total = 0;

    for($i = $range_min; $i <= $range_max; $i++)
    {
        if(isset($number[$cat][$bool][$i]))
        {
            $total += $number[$cat][$bool][$i];
        }
    }

    return $total;
}

 

I am trying just to use the range function and want to get rid of the first part of the code since it is causing problems in my code. Part two seems to be dependent on part one however...Could your perhaps help me to incorporate part one directly in part two only for the range function?

Link to comment
Share on other sites

By incorporate do you mean merge the two pieces of code together? If thats the case then try:

function get_numbers($file) // this function builds the $numbers array
{
    $contents = file($file);
    foreach($contents as $line_value)
    {
        list($cat, $int, $id, $num) = explode("\t", $line_value);

        $cat = str_replace('#', '', $cat);

        $number[$cat][$int][$id] = trim($num);
    }

    return $numbers;
}

function calculate_range($source_file, $cat, $bool, $range_min, $range_max)
{
    $numbers = get_numbers($source_file); // get the numbers from a source file

    $total = 0;

    for($i = $range_min; $i <= $range_max; $i++)
    {
        if(isset($number[$cat][$bool][$i]))
        {
            $total += $number[$cat][$bool][$i];
        }
    }

    return $total;
}

$file    = $_FILES['userfile']['name']; // the source file
$total   = calculate_range($file, 'UB', -1, 1600, 1650); // calculate the range

All I've done is added an extra parameter for the calculate_range function which will be used to pass the source file. This parameter will be passed over to the get_numbers function which will generate the numbers array.

Link to comment
Share on other sites

<?php

function calculate_range($source_file, $cat, $bool, $range_min, $range_max)
{
    $contents = file($file);
    foreach($contents as $line_value)
    {
        list($_cat, $_bool, $_id, $num) = explode("\t", $line_value);

        $_cat = str_replace('#', '', $_cat);

        $number[$_cat][$_bool][$_id] = trim($num);
    }

    $total = 0;
    for($i = $range_min; $i <= $range_max; $i++)
    {
        if(isset($number[$cat][$bool][$i]))
        {
            $total += $number[$cat][$bool][$i];
        }
    }

    return $total;
}

$file    = $_FILES['userfile']['name'];                  // the source file
$total   = calculate_range($file, 'UB', -1, 1600, 1650); // calculate the range

?>

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.