php - 如何限制特定数组键打印的字符数

标签 php mysql arrays pdo html-table

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

最佳答案

在此处添加条件:

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

关于php - 如何限制特定数组键打印的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12831603/

相关文章:

php - 如何将表单数据提交到MySQL数据库

php - PDO登录系统

mysql - 有 > 运算符时,我需要什么样的索引?

java - 获取预选结果

c - 使用 %s(即字符串说明符)读取 char 数组

php - Ajax 调用上的服务器端重新加载启动

php 如果小写字母前面没有空格,则将字符串分解为大写

php - 我需要使用数据库中的特定字符创建自定义查询

java - 为什么我们在java中使用string.charAt(index) -'a'?

php - Doctrine mysql,检查数组是否在其他数组中