duanba7498 2019-03-29 09:07
浏览 158

如何在while循环中使用json_encode?

I've a litle probleme with my loop. I've to do a while loop because i encode really big files. But if I encode row per row I create every time a new JSON Object.

So Now I've this output.

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

But I need something like this:

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

And with this code I create this JSON-File:

$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);
  • 写回答

1条回答 默认 最新

  • doulang7699 2019-03-29 13:38
    关注

    So I decided to make my own "encoder", and just writing it in the File. Heres the final code wich worked for me.

    $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] .'" , '. "
    " . '  "1" : "'. $matches[0][1] .'", '. "
    " . ' "2" : "'. $matches[0][2] .'"}'. "
    " . '');
                }
                else
                {
                    fwrite($jsonFile, ',{"0" : "'. $matches[0][0] .'" , '. "
    " . '  "1" : "'. $matches[0][1] .'", '. "
    " . ' "2" : "'. $matches[0][2] .'"}'. "
    " . ''); 
                }
                $i++;
    
            }
        }
        fwrite($jsonFile, "]");
    
    
    //var_dump($decodeData);
    }
    fclose($handle);
    fclose($jsonFile);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接