2016-07-14 35 views
2

因此,我有一個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; 

如果某一個值DateDateTime然後我得到的錯誤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; 

所以,讓我們說,我想寫的任何查詢結果中,我無法事先什麼記錄有什麼類型的告訴一般的功能。我如何準備代碼來處理日期?

+1

您可以使用if($ res [$ i] [$ j] instanceof DateTime)'來檢查是否有日期,然後以不同的方式處理它。 –

回答

2

可以使用is_a功能檢查是否它的日期時間對象,並處理它

if (is_a($res[$i][$j], 'DateTime')) { 
// handle code 
} 
1

你可以編寫自己的錯誤處理程序捕獲異常,只要你想。

function errorHandler($errno, $errstr, $errfile, $errline) { 
    if (E_RECOVERABLE_ERROR===$errno) { 
     echo "'catched' catchable fatal error\n"; 
     throw new Exception(); 
    } 
    return false; 
} 
set_error_handler('errorHandler'); 


$t = new DateTime(); 
try{ 
    $table = "<td>".$t."</td>"; 
}catch(Exception $e){ 
    $table = "<td>".$t->format("Y-m-d H:i:s")."</td>"; 
} 

echo $table; 

這樣就會拋出一個可以捕捉的異常。它會輸出

'catched' catchable fatal error 
<td>2016-07-14 12:57:27</td>%