簡體   English   中英

如何在while循環中使用json_encode?

[英]How can I use json_encode in a while loop?

我的循環問題一直存在。 我要做一個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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM