2012-10-11 25 views
0

下面的腳本打印使用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"; 
?> 

這工作得很好,但關鍵之一在數組包含一些段落文本很長。一個例子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循環中添加該條件。任何提示將不勝感激。

回答

2

這裏補充一個條件:

foreach ($row as $key => $val){ 
    print "<td>$val</td>"; 
} 

你會檢查,看它是否超過五十個字符:

$truncate_keys = array("task"); 
foreach ($row as $key => $val){ 
    if (strlen($val) > 50 && in_array($key, $truncate_keys)) { 
     print "<td>" . substr($val, 0, 50) . "...</td>"; 
    } else { 
     print "<td>$val</td>"; 
    } 
} 

警告:此方法將單詞的中途被切斷。這個問題已經得到解決,並且以更好的方式;例如,this CodeIgniter helper有一個解決方案,據稱可以保持文字不變。

+0

謝謝!這是有道理的 - 但是我怎樣才能使這隻適用於其中一個鍵(任務)? –

+0

@DanielC編輯。 –