[英]PHP: Read TXT file and make each line a variable (split line with ,) (This is for a user ranking system)
[英]PHP for each line in TXT, increase value of variable?
我有以下代码用于读取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);
?>
我现在想插入$ hr #min和$ sec变量,每次保存新行时它们将增加1秒。 假设我的代码行是这样的(旧代码):
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);
?>
我会轻松得多:
<?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);
我认为您正在内部循环中寻找类似的内容:
$sec++;
if (($sec==60) {
$min++;
$sec=0
if (($min==60) {
$hr++;
$min=0;
if (($hr==25) { $hr=0; }
}
}
您使用的格式具有UNIX域中的日期,例如,第一个日期:
gmdate('His', 0); # 000000
gmdate('His', 60); # 000100
gmdate('His', 3600); # 010000
因此,您只需输入秒数,gmdate函数就会为您设置格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.