从PHP日志文件中提取Json数据并添加新列

时间:2016-05-26 06:55:25

标签: php json parsing csv

我是php的新手, 这是我的json文件,

{"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":326195011},"route_name":["",""],"via_indices":[0,15],"via_points":[[25.299982,55.376873],[25.29874,55.369179]],"found_alternative":false,"route_summary":{"end_point":"","start_point":"","total_time":101,"total_distance":871},"route_geometry":"{_ego@m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli@hsEfFzn@QlTgNhwCs@fKwBjF","status_message":"Found route between points","status":0}

我只需要从json中提取 total_time 并将提取的total_time打印到csv文件中的新列,有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

我认为你需要这些。

$json = '{"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":326195011},"route_name":["",""],"via_indices":[0,15],"via_points":[[25.299982,55.376873],[25.29874,55.369179]],"found_alternative":false,"route_summary":{"end_point":"","start_point":"","total_time":101,"total_distance":871},"route_geometry":"{_ego@m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli@hsEfFzn@QlTgNhwCs@fKwBjF","status_message":"Found route between points","status":0}';
$assoc = true;
$result = json_decode ($json, $assoc);
$result['total_time'] = $result['route_summary']['total_time'];

$json = json_encode($result);

现在是时候使用$json将这些file_put_contents放回文件。

file_put_contents('file.csv', $json );

答案 1 :(得分:0)

将json字符串保存到json文件中,加载它,然后使用json_decode函数将其作为数组加载到PHP中。

        var time_api= this.api();

        var total= tempo.column(3)
                .data()
                .sum();            
        total= total.toString();       
        while (total.length < 6){
           tempoTotal = "0" + tempoTotal   
        }    

        total= total.replace(/^(\d+)(\d{2})(\d{2})$/, function(m, m1, m2, m3) {
            m1 = Number(m1); // convert captured group value to number
            m2 = Number(m2);
            m2 += parseInt(m3 / 60, 10); // get minutes from second and add it to minute
            m3 = m3 % 60; // get soconds
            m1 += parseInt(m2 / 60, 10); // get minutes from minute and add it to hour
            m2 = m2 % 60; // get minutes
            // add 0 to minute and second if single digit , slice(-2) will select last 2 digit
            return m1 + ':' + ('0' + m2).slice(-2) + ':' + ('0' + m3).slice(-2); // return updated string
        })

        //write in footer
        $(tempo.column(3)
            .footer())
            .html(total);

如何将结果导出到CSV文件,然后在SO上有示例here