【问题标题】:How to limit the number of characters printed for a particular array key如何限制为特定数组键打印的字符数
【发布时间】:2012-10-01 15:33:03
【问题描述】:

下面的脚本使用 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 循环中添加该条件。任何提示将不胜感激。

【问题讨论】:

    标签: php mysql arrays pdo html-table


    【解决方案1】:

    在此处添加条件:

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

    您将检查它是否超过 50 个字符:

    $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 有一个据称可以保持文字完整的解决方案。

    【讨论】:

    • 谢谢!这是有道理的 - 但是我怎样才能让它只适用于其中一个键(任务)?
    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2020-04-18
    相关资源
    最近更新 更多