我的循环有点问题。我要做一个while循环因为我编码非常大的文件。但是如果我每行编码一行,我每次都会创建一个新的JSON对象。
所以现在我有了这个输出。
[
[
"some logs and soo with informations ",
"00:59:59",
"the pure logssdf"
]
][
[
"some logs and soo with informations ",
"00:59:52",
"the pure logssdf"
]
]
但是我需要这样的东西:
[
{
"some logs and soo with informations ",
"00:59:52",
"the pure logssdf"
},{
"some logs and soo with informations ",
"00:59:52",
"the pure logssdf"
}
]
使用此代码,我创建了这个JSON文件:
$jsonFile = fopen('JSONLogs/' . $generatedName, "w");
$handle = @fopen($PATHTOLOG, "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$pattern = '/^\w+\s+\d+\s('. preg_quote($SelectedTime) .':\d+.\d+).\d+.\d+\s(.+)/im';
if (preg_match_all($pattern, $buffer, $matches, PREG_SET_ORDER)) {
fwrite($jsonFile, json_encode($matches, JSON_PRETTY_PRINT));
}
else {
}
}
//var_dump($decodeData);
}
fclose($handle);
fclose($jsonFile);
所以我决定制作自己的“编码器”,并将其写入文件中。这是最终的代码,对我有用。
$jsonFile = fopen('JSONLogs/' . $generatedName, "w");
$i=0;
$handle = @fopen($PathToTMP, "r");
if ($handle) {
fwrite($jsonFile, "[");
while (($buffer = fgets($handle, 4096)) !== false) {
$pattern = '/^\w+\s+\d+\s('. preg_quote($SelectedTime) .':\d+.\d+).\d+.\d+\s(.+)/im';
if (preg_match_all($pattern, $buffer, $matches, PREG_SET_ORDER)) {
if ($i == 0) // Run this if block once.
{
fwrite($jsonFile, '{"0" : "'. $matches[0][0] .'" , '. "\n" . ' "1" : "'. $matches[0][1] .'", '. "\n" . ' "2" : "'. $matches[0][2] .'"}'. "\n" . '');
}
else
{
fwrite($jsonFile, ',{"0" : "'. $matches[0][0] .'" , '. "\n" . ' "1" : "'. $matches[0][1] .'", '. "\n" . ' "2" : "'. $matches[0][2] .'"}'. "\n" . '');
}
$i++;
}
}
fwrite($jsonFile, "]");
//var_dump($decodeData);
}
fclose($handle);
fclose($jsonFile);