query($sql); $sites = $rs->fetchAll(); //先为该数据创建一个文件夹 $datapath=$basepath.$uuid; if (!file_exists($datapath)) { $result = mkdir($datapath); } //有需要生成的数据 if($sites) { foreach($sites as $k=>$v ) { //逐个site生成 $site = $v['site']; //获取观测点的名称 $sitename= $v['fld_name']; //在该文件夹下面再建立一个观测点文件夹 $sitepath=$datapath.DIRECTORY_SEPARATOR.$sitename; if (!file_exists($sitepath)) { $result = mkdir($sitepath); } //获取变量名称 $sql="select distinct va.fld_name from tbl_site_sensor_variable ssv left join tbl_variable_info va on ssv.fld_variable_id=va.fld_variable_id WHERE ssv.fld_site_id=$site order by va.fld_name"; $sth=$db->query($sql); $rs=$sth->fetchAll(); if (!$rs) continue; $head = "Time"; $sql2= "select * from crosstab('SELECT v.fld_time as time,va.fld_name as variablename,v.fld_value as value FROM tbl_value v left join tbl_variable_info va on v.fld_variable_id=va.fld_variable_id WHERE v.fld_site_id=$site ORDER BY time', 'select distinct va.fld_name from tbl_variable_info va left join tbl_site_sensor_variable v on v.fld_variable_id=va.fld_variable_id WHERE v.fld_site_id=$site order by va.fld_name') as ct(time timestamp without time zone"; foreach($rs as $k=>$var) { $head.=", ".$var['fld_name']; $sql2.=",v".$k." real"; } $head.="\n"; $sql2.=")"; //获取数据 $sth2 = $db->query($sql2); $html=""; $datastart=true; $start=""; while ($v=$sth2->fetch()) { //组装数据 if ($datastart) { $start=$v['time']; $endtime=date("Y-m-d",strtotime($start)+24*3600); $datastart=false; $html=""; } if ($v['time']>=$start && $v['time']<$endtime) { $html.=$v['time']; foreach ($rs as $k=>$var) $html.=",".$v['v'.$k]; $html.="\n"; } elseif ($v['time']>=$endtime) { //写入文件 $resulttime=date("Ymd",strtotime($start)); $fp = fopen($sitepath.DIRECTORY_SEPARATOR.$sitename.$resulttime.".CSV","w+"); fwrite($fp,$head.$html); //写入数据 fclose($fp); //关闭文件句柄 $datastart=true; } } if (!$datastart) { //写入最后的文件 $resulttime=date("Ymd",strtotime($start)); $fp = fopen($sitepath.DIRECTORY_SEPARATOR.$sitename.$resulttime.".CSV","w+"); fwrite($fp,$head.$html); //写入数据 fclose($fp); //关闭文件句柄 } print $sitename."\r\n"; } }