PHP '非法字符串偏移'在 foreach 循环中 [英] PHP 'Illegal string offset' in foreach loop
问题描述
我正在使用 PDO 从 MySQL 数据库获取一个关联数组.
I am getting an assoc array from a MySQL database using PDO.
我想使用以下代码对其执行一个函数来减少单词数:
I want to perform a function on it to trim down the number of words by using the following code:
$newsContent = Words::truncateWords($rows);
我收到此错误并且该功能无效
I am getting this error and the the function hasn't worked
Warning: Illegal string offset 'content' in C:\www\mvc\libs\Words.php on line14
Warning: Illegal string offset 'content' in C:\www\mvc\libs\Words.php on line 14
注意:未初始化的字符串偏移量:0 in C:\www\mvc\libs\Words.php on第 14 行
Notice: Uninitialized string offset: 0 in C:\www\mvc\libs\Words.php on line 14
警告:C:\www\mvc\libs\Words.php 中的非法字符串偏移内容"第 14 行
Warning: Illegal string offset 'content' in C:\www\mvc\libs\Words.php on line 14
第一个错误大约重复了 8 次.第14行指向这条线
The first error is repeated about 8 times. Line 14 points to this line
$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;
}
}
推荐答案
这是因为 content 不是 $row
的下标,先检查一下是不是.
This is because content is not a subscript of $row
Check first and see if it is.
array_key_exists
检查变量是否设置,但不检查该变量不为空
array_key_exists
checks if the variable is set, but it does not check that variable is NOT null
if(array_key_exists('content', $row) {
self::trunc($row['content'], 60);
}
要检查下标是否存在且不为空,请使用isset
To check that the subscript exists and is not null, use isset
这篇关于PHP '非法字符串偏移'在 foreach 循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!