我正在使用PDO从MySQL数据库中获取一个assoc数组。
我想使用以下代码对其执行一个功能以减少单词数:
$newsContent = Words::truncateWords($rows);
我收到此错误,并且该功能不起作用
警告:在线 C:\www\mvc\libs\Words.php 中的非法字符串偏移"内容" 14
注意:未初始化的字符串偏移量:0 在 C:\www\mvc\libs\Words.php on 14号线
警告:C:\www\mvc\libs\Words中的非法字符串偏移量"内容.php 在第 14 行
第一个错误重复约8次。 第 14 行指向此行
$rows[$key]['content'] = self::trunc($row['content'], 60);
这是我的单词课
class Words {
// truncate each of the news item's content to a set number of words
public static function truncateWords($rows) {
// loop through the array
foreach($rows as $key => $row) {
// and truncate content to 60 words
$rows[$key]['content'] = self::trunc($row['content'], 60);
}
return $rows;
}
public function trunc($phrase, $max_words)
{
$phrase_array = explode(' ',$phrase);
if(count($phrase_array) > $max_words && $max_words > 0)
$phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';
return $phrase;
}
}
这是因为内容不是$row
的下标 首先检查一下,看看它是否是。
array_key_exists
检查变量是否已设置,但不检查变量是否为空
if(array_key_exists('content', $row) {
self::trunc($row['content'], 60);
}
若要检查下标是否存在且不为 null,请使用 isset