Page 1 of 1

Split and summ data in .txt file

Posted: Sat Nov 22, 2008 4:37 am
by roime
Hi all,

I have a problem on php coding. I have a text file that consists of a data like this

joe.txt;
12
34
32
34
21
23

By using php, i try to split the data into a separated group that consists 2 values such a format like below;

group 1;
12
34

group 2;
32
34

group 3;
21
23

I've successfully writes a script to read all of the values, display them and sum all of them..But i still refused to split them and sum all of them based on their groups..If u guys have an idea then please help me...

Scripts that i had;
<?php
$myFile = "joe.txt";
$handle = fopen($myFile, 'r');
while (!feof($handle))
{
$data = fgets($handle, 512);
echo $data;
echo "<br>";
$total += $data;
}
fclose($handle);
$lines = count(file($myFile));
echo "There are $lines lines in $myFile";
echo "<br>";
echo "Total value was : $total";

?>

Re: Split and summ data in .txt file

Posted: Sat Nov 22, 2008 5:40 am
by koen.h
Can you write here what your intended output is?

eg
echo "There are $lines lines in $myFile";
echo "<br>";
echo "Total value was : $total";
foreach ($groups as $group)
{
echo "$group total value: $value";
}

Re: Split and summ data in .txt file

Posted: Sat Nov 22, 2008 12:53 pm
by roime
Thanks for your reply. Basically, I want the script read the file for every 2 values, doing looping in every next 2 value and doing sum. The txt file defined as;
joe.txt;
12
34
32
34
21
23

And after the execution, they could be able to display a data like this;
46
66
44

which means every 2 value are added consequently.

I dont have any idea what method to do that but the pseudo could be like this;

read line;
loop{
foreach 2 line
total+=value;
}

Re: Split and summ data in .txt file

Posted: Sat Nov 22, 2008 5:00 pm
by koen.h
A possible trick is to use a counter. Let it count to 2 and reset it, or let it count and check if the value is divisable by 2.

eg:

Code: Select all

 
$i = 1;
while (!feof($handle))
{
    $data = fgets($handle, 512);
    echo "$i = $data";
    echo "<br>";
    if ($i = 2)
    {
        $total = $previous + $data;
        echo "total: {$total}<br />";
        $i = 0;
    }
    $previous = $data;
    $i++;
}
 

Re: Split and summ data in .txt file

Posted: Mon Nov 24, 2008 4:35 am
by roime
Hi Koen.h,

Thanks again. After made some modification on ur snippet, it gave me a big smile...Here is the code to share;
<?php
$myFile = "joe.txt";
$handle = fopen($myFile, 'r');
$i=1;
$prev=0;
$tot=0;
while (!feof($handle))
{
$data = fgets($handle, 512);
echo $data;
echo "<br>";
if($i==2){
$total = $data + $previous;
$tot = $total - $prev;
echo "total: {$tot}<br />";
$i = 0;
}
$previous += $data;
$prev = $total;

$i++;
}
fclose($handle);
$lines = $i;
$lines = count(file($myFile));
echo "There are $lines lines in $myFile";
echo "<br>";
?>

And here is the sample result;
23
45
total: 68
67
54
total: 121
32
12
total: 44
There are 6 lines in joe.txt
Once again, thanks