php - 基于值列的文本文件上的PHP计数行/行
问题描述
继续我之前的问题。
我有一个名为拒绝的文本日志文件。你可以在这里看到
如您所见,选项卡上有 4 个步骤:
1. Battery level
2. Piezo sound level
3. Left D3 (Ch 3) light intensity
4. Right D2 (Ch 1) light intensity
现在我想用条件计算每一行:
Which column(Steps) value is filled then count it.
Example: on row 1, We can see the value 0 (any value) is on step Piezo sound level. Then count it.
所以最后我可以知道有多少数量的拒绝过程。
Battery level = x quantity
Piezo sound level = x quantity
Left D3 (Ch 3) light intensity = x quantity
Right D2 (Ch 1) light intensity = x quantity
PHP代码:
$fromDateTime = new DateTime('Wed, Sep 19 2018 08:00:00');
$toDateTime = new DateTime('Wed, Sep 19 2018 19:59:00');
$file = file_get_contents('reject.txt');
$lines = explode("\n",$file);
// counter
$rowsintimespan = 0;
// Do Line-By-Line starting by Line 16 (Array Index 15)
for($i = 15; $i < count($lines); $i++) {
// if the file is "Tue, Sep 18<tab>2018<tab>23:59:53<tab>"
$dateobj = DateTime::createFromFormat("???,?M?d??Y?H:i:s+", $lines[$i]);
// check if date is in your Timespan
if($dateobj < $toDateTime && $dateobj > $fromDateTime) {
$rowsintimespan++; // count if in timespan
}
}
// Debug-Output
echo $rowsintimespan;
更新
我需要读取最后一列的值,例如:如果行的值在左 D3 列上,则对其进行计数。如果行的值在压电列上,则计算它。
解决方案
如果您可以将列写为键,那么这应该如您所描述的那样工作:
$fromDateTime = new DateTime('Wed, Sep 19 2018 08:00:00');
$toDateTime = new DateTime('Wed, Sep 19 2018 19:59:00');
$file = file_get_contents('Reject.txt');
$lines = explode("\n", $file);
// counter
$rowsintimespan = 0;
// keys should correspond to columns
$keys = [
'date',
'time',
'battery',
'piezo',
'leftD3',
'rightD2'
];
$values = array_fill(0, count($keys), 0);
$values = array_combine($keys, $values);
// Do Line-By-Line starting by Line 16 (Array Index 15)
for ($i = 11; $i < count($lines); $i++) {
// if the file is "Tue, Sep 18<tab>2018<tab>23:59:53<tab>"
$dateobj = DateTime::createFromFormat("???,?M?d??Y?H:i:s+", $lines[$i]);
// check if date is in your Timespan
if ($dateobj < $toDateTime && $dateobj > $fromDateTime) {
$rowsintimespan++; // count if in timespan
// get line elements
$lineContent = explode("\t", $lines[$i]);
// loop through line elements and count them
$x = 0;
for ($j = 0; $j < count($keys); $j++) {
if (!isset($lineContent[$j])) {
continue;
}
// remember position of last not empty column
if (trim($lineContent[$j]) != '') {
$x = $j;
}
}
if ($x > 0) {
$values[$keys[$x]]++;
}
}
}
// Debug-Output
echo $rowsintimespan;
// Output every column
echo '<pre>';
print_r($values);
这将打印出:
Array
(
[date] => 0
[time] => 0
[battery] => 4
[piezo] => 31
[leftD3] => 17
[rightD2] => 1
)
推荐阅读
- python-3.x - PyMesh 中是否有计算体积的函数?
- java - java - 为什么无法将一个类的getter方法识别为java中的另一个类?
- docker - 使用 docker 部署 nodejs、mongodb、redis 应用
- javascript - Firebase Firestore 不会持久化数组
- java - 重构 - 将相似或不同实体的 arrayList 值放入的代码
- sql - 查询用户发布条目次数的最佳方法
- reactjs - 对 SelectInput 使用 combineValidators 来验证 Guid.Empty
- html - 即使我最小化屏幕,如何在 HTML/CSS 中绝对修复文本
- terminal - 如何独立于终端运行 Electron 应用程序?
- laravel - 雄辩的急切加载关系