如何在while循环中使用json_encode?

时间:2019-03-29 09:07:31

标签: php json while-loop

我的循环有点麻烦。我必须做一会儿循环,因为我对很大的文件进行编码。但是,如果我对每行进行编码,那么每次都会创建一个新的JSON对象。

所以现在我有了这个输出。

date

但是我需要这样的东西:

[
    [
        "some logs and soo with informations ",
        "00:59:59",
        "the pure logssdf"
    ]
][
    [
        "some logs and soo with informations ",
        "00:59:52",
        "the pure logssdf"
    ]
]

并使用此代码创建此JSON文件:

[
            {
               "some logs and soo with informations ",
               "00:59:52",
               "the pure logssdf"
            },{
               "some logs and soo with informations ",
               "00:59:52",
               "the pure logssdf"
            }
]

1 个答案:

答案 0 :(得分:0)

因此,我决定制作自己的“编码器”,然后将其写入文件中。这是最终为我工作的代码。

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