1

次のコードで TXT ファイルを読み取り、各行から不要な情報を取り出し、編集した行を新しい 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) が続き、最後に抽出された txt があります。

変数フレームワークを作成しましたが、変数を適切にインクリメントする方法がわかりません。誰か助けてくれませんか?

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

3 に答える 3

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);
于 2012-04-12T19:56:49.937 に答える
0

内側のループで次のようなものを探していると思います:

$sec++;
if (($sec==60) { 
    $min++; 
    $sec=0 
    if (($min==60) { 
        $hr++; 
        $min=0; 
        if (($hr==25) { $hr=0; }
    }
}
于 2012-04-12T19:48:45.797 に答える
0

あなたが持っているフォーマットは、UNIXドメインの日付です。たとえば、最初の日付です。

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

したがって、秒数を渡すだけで、gmdate 関数がフォーマットしてくれます。

于 2012-04-12T19:55:46.677 に答える