因此,我有一個SQL
查詢結果加載到一個array
。現在,我想在html
表中顯示它。這是我以前使用的代碼。準備日期時間的PHP代碼
$table = "<table><thead><tr><th>".implode('</th><th>', array_keys(current($res)))."</th></tr></thead><tbody>";
for($i = 0; $i < count($res); ++$i) {
$table .= "<tr>";
for($j = 0; $j < count($res[$i]); ++$j) {
$table .= "<td>".$res[$i][$j]."</td>"; //here is the issue if it's date
}
$table .= "</tr>";
}
$table .= "</tbody></table>";
echo $table;
如果某一個值Date
或DateTime
然後我得到的錯誤Catchable fatal error: Object of class DateTime could not be converted to string
。
這是我的下一步導致完全相同的錯誤。我不明白爲什麼。
$table = "<table><thead><tr><th>".implode('</th><th>', array_keys(current($res)))."</th></tr></thead><tbody>";
for($i = 0; $i < count($res); ++$i) {
$table .= "<tr>";
for($j = 0; $j < count($res[$i]); ++$j) {
try {
$table .= "<td>".$res[$i][$j]."</td>"; //the issue is here again, so try doesn't seem to work as expected
}
catch (Exception $e){
$table .= "<td>".$res[$i][$j]->format('Y-m-d H:i:s')."</td>";
}
}
$table .= "</tr>";
}
$table .= "</tbody></table>";
echo $table;
所以,讓我們說,我想寫的任何查詢結果中,我無法事先什麼記錄有什麼類型的告訴一般的功能。我如何準備代碼來處理日期?
您可以使用if($ res [$ i] [$ j] instanceof DateTime)'來檢查是否有日期,然後以不同的方式處理它。 –