以下のスクリプトは、PDO を使用した MySQL クエリに基づいてテーブルを出力します。
<?php
//PDO start
$dbh = new PDO(...);
$stmt = $dbh->prepare($query);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$arrValues = $stmt->fetchAll();
//create table
print "<table> \n";
print "<tr>\n";
//add table headers
foreach ($arrValues[0] as $key => $useless){
print "<th>$key</th>";
}
print "</tr>";
//add table rows
foreach ($arrValues as $row){
print "<tr>";
foreach ($row as $key => $val){
print "<td>$val</td>";
}
print "</tr>\n";
}
//close the table
print "</table>\n";
?>
これは正常に機能しますが、配列内のキーの 1 つに非常に長い段落テキストが含まれています。vardump の例を以下に示します。
array
0 =>
array
'Name' => string 'John' (length=5)
'Day' => string 'Monday' (length=6)
'Task' => string 'This is a really long task description that is too long to be printed in the table' (length=82)
'Total Hours' => string '5.00' (length=4)
「タスク」キーで最初の 50 文字のみを出力し、最後に「...」を付けたいと思います。foreach ループ内にその条件を追加する方法がわかりません。ヒントをいただければ幸いです。