我有一个如下工作的PHP代码,它使用来自mysql数据库的数据填充数组。它用于生成一个表,作为回报,在另一个php文件中使用它来生成谷歌图表。 但我需要重新格式化“时间戳”中的数据。字段,使用函数JSdate($ in,$ type)。作为一个菜鸟,当谈到PHP,我该怎么做?我想它应该在你遍历数据库中每条记录的部分完成,而不仅仅是写“时间戳”,它应该说是JSdate('时间戳',' datetime'),但我无法让它工作。对于有更多PHP经验的人来说可能是一个简单的问题; - )
function JSdate($in,$type){
if($type=='date'){
//Dates are patterned 'yyyy-MM-dd'
preg_match('/(\d{4})-(\d{2})-(\d{2})/', $in, $match);
} elseif($type=='datetime'){
//Datetimes are patterned 'yyyy-MM-dd hh:mm:ss'
preg_match('/(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})/', $in, $match);
}
$year = (int) $match[1];
$month = (int) $match[2] - 1; // Month conversion between indexes
$day = (int) $match[3];
if ($type=='date'){
return "Date($year, $month, $day)";
} elseif ($type=='datetime'){
$hours = (int) $match[4];
$minutes = (int) $match[5];
$seconds = (int) $match[6];
return "Date($year, $month, $day, $hours, $minutes, $seconds)";
}
}
try {
$dbname = 'database'; // Add your Database name here
$username = 'XXXXXX'; // Add your Username here
$password = 'XXXXXXX'; // Add your password here
$conn = new PDO("mysql:host=XXXXXXXXX;dbname=$dbname", $username,$password);
echo "Connected successfully";
}catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// First section of code is for generating data for Google Charts.
try {
$result = $conn->query('SELECT *
FROM tempdata_ny
WHERE Timestamp > DATE_SUB(NOW(), INTERVAL 1000 HOUR)');
// Create the variables for the Google Chart and define as arrays
$rows = array();
$table = array();
// Define the array labels
$table['cols'] = array(
array('label' => 'Datetime', 'type' => 'string'),
array('label' => 'Temp1', 'type' => 'number'),
array('label' => 'Temp2', 'type' => 'number')
);
// Iterate through each record in the MySQL DB to populate the array
foreach($result as $r) {
$data = array();
$data[] = array('v' => (string) $r['Timestamp']);
$data[] = array('v' => (float) $r['Temp_Sens1']);
$data[] = array('v' => (float) $r['Temp_Sens2']);
// print "<pre>";
// print_r($data);
// print_r($r);
// print "</pre>";
// Insert data array into $rows
$rows[] = array('c' => $data);
}
$table['rows'] = $rows;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
答案 0 :(得分:0)
更改
$data[] = array('v' => (string) $r['Timestamp']);
有关
$data[] = array('v' => (string) JSdate($r['Timestamp'],'datetime'));