![](/img/trans.png)
[英]How to get number of occurrences of a particular Key inside an array in PHP?
[英]How to limit the number of characters printed for a particular array key
下面的脚本使用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)
我想让'Task'键只打印前50个字符并在末尾加上'...'。 我不确定如何在foreach循环中添加该条件。 任何提示将不胜感激。
在这里添加一个条件:
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>";
}
}
请注意:这种方法会在文字中间切断。 这个问题已经以更好的方式解决了; 例如, 这个CodeIgniter帮助程序有一个解决方案,据称保持单词完整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.