2012-04-12 92 views
1

我有以下代碼,讀取一個TXT文件,從每一行中取出不需要的信息,然後將編輯的行存儲在一個新的TXT文件中。對於TXT中的每一行PHP,增加變量的值?

<?php 
$file_handle = fopen("old.txt", "rb"); 
ob_start(); 

while (!feof($file_handle)) { 

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

foreach ($parts as $str) { 
$str_parts = explode('_', $str); // Split string by _ into an array 
array_pop($str_parts); // Remove last element 
array_shift($str_parts); // Remove first element 
echo implode('_', $str_parts)."\n"; // Put it back together (and echo newline) 
} 
} 

$new_content = ob_get_clean(); 
file_put_contents("new.txt", $new_content); 

fclose($file_handle); 
?> 

我現在想要插入$ hr #min和$ sec變量,每次保存新行時將增加1秒。比方說,我的臺詞這樣寫的(舊代碼):

958588 
978567 
986766 

我想我的新的代碼看起來像這樣:

125959958588 
130000978567 
130001986766 

正如你所看到的,一小時是24小時格式(00 - 23),然後是分鐘(00-59)和秒(00-59),結束時提取的txt。

我放下了可變框架,但我不知道如何讓vriables正確增加。有人可以幫忙嗎?

<?php 
$file_handle = fopen("old.txt", "rb"); 
$hr = 00; 
$min = 00; 
$sec = 00; 
ob_start(); 

while (!feof($file_handle)) { 

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

foreach ($parts as $str) { 
$str_parts = explode('_', $str); // Split string by _ into an array 
array_pop($str_parts); // Remove last element 
array_shift($str_parts); // Remove first element 
echo $hr.$min.$sec.implode('_', $str_parts)."\n"; // Put it back together (and echo newline) 
} 
} 

$new_content = ob_get_clean(); 
file_put_contents("new.txt", $new_content); 

fclose($file_handle); 
?> 
+0

在什麼時候一定時間計數器開始? – elxordi 2012-04-12 19:48:33

+0

這個尖叫出來 - 使用數據庫,而不是一個平面文件。 – 2012-04-12 19:48:50

+0

我無法使用數據庫,我必須解析文件 – Sweepster 2012-04-12 19:51:15

回答

1

我會去要容易得多:

<?php 
$contents = file('old.txt'); 
$time = strtotime('2012-01-01 00:00:00'); // Replace the time with the start time, the date doesn't matter 
ob_start(); 

foreach ($contents as $line) { 
    $str_parts = explode('_', $line); // Split string by _ into an array 
    array_pop($str_parts); // Remove last element 
    array_shift($str_parts); // Remove first element 

    echo date('His', $time) . implode('_', $str_parts) . "\n"; // Put it back together (and echo newline) 

    $time += 1; 
} 

$new_content = ob_get_clean(); 
file_put_contents("new.txt", $new_content); 
+0

這樣做了!謝謝! – Sweepster 2012-04-12 20:05:48

+0

不客氣:) – elxordi 2012-04-12 20:08:22

0

我認爲你正在尋找一個在內部循環是這樣的:

$sec++; 
if (($sec==60) { 
    $min++; 
    $sec=0 
    if (($min==60) { 
     $hr++; 
     $min=0; 
     if (($hr==25) { $hr=0; } 
    } 
} 
+0

秒必須爲00格式。我怎樣才能做到這一點? – Sweepster 2012-04-12 19:52:02

+0

使用printf或sprintf,如下所示: printf(「%2d%2d%2d」,$ sec,$ min,$ hr); – Leven 2012-04-12 19:56:39

0

你擁有的格式是UNIX域的日期,例如第一次約會:

gmdate('His', 0); # 000000 
gmdate('His', 60); # 000100 
gmdate('His', 3600); # 010000 

所以你可以傳遞秒數,gmdate函數會爲你設置格式。