2012-04-12 6 views
1

次のコードを読んでTXTファイルを読み込み、不要な情報を各行から取り出して、新しいTXTファイルに保存します。PHPはTXTの各行に変数の値を増やしますか?

<?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); 
?> 

新しい行が保存されるたびに1秒ずつ増加する$ hr #minと$ sec変数を挿入します。のは、私の行は次のように(古いコード)を読み取るとしましょう:

958588 
978567 
986766 

私は私の新しいコードは次のようになりたい:あなたが見ることができるように

125959958588 
130000978567 
130001986766 

、時間は24時間形式です(00 - 23)、続いて分(00 - 59)、秒(00 - 59)の順に抽出されます。

私は可変フレームワークを説明しましたが、変数を正しくインクリメントする方法はわかりません。助けてもらえますか?

<?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

+0

これはフラットファイルではなく、データベースを使用して叫びます。 –

+0

データベースを使用できません。ファイルを解析する必要があります。 – Sweepster

答えて

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

+0

あなたは大歓迎です:) – elxordi

0

私はあなたが内側のループでは、このような何かを探していると思う:

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

秒は00形式でなければなりません。どうやってやるの? – Sweepster

+0

printfまたはsprintfを使用してください。 printf( "%2d%2d%2d"、$ sec、$ min、$ hr); – Leven

0

あなたが持っているフォーマットは、例えば、第1日、UNIXドメインの日付は次のとおりです。

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

これで秒数を渡すだけで、gmdate関数によってフォーマットされます。

関連する問題