【问题标题】:PHP 'Illegal string offset' in foreach loopforeach循环中的PHP“非法字符串偏移”
【发布时间】:2013-09-29 21:48:04
【问题描述】:

我正在使用 PDO 从 MySQL 数据库中获取一个 assoc 数组。

我想通过以下代码对其执行一个函数来减少单词的数量:

$newsContent = Words::truncateWords($rows);

我收到此错误并且该功能不起作用

警告:在线 C:\www\mvc\libs\Words.php 中存在非法字符串偏移“内容” 14

注意:未初始化的字符串偏移量:0 在 C:\www\mvc\libs\Words.php 上 第 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;
    }
}

【问题讨论】:

    标签: php arrays class oop foreach


    【解决方案1】:

    这是因为内容不是$row的下标先检查一下是不是。

    array_key_exists 检查变量是否已设置,但不检查变量是否为空

    if(array_key_exists('content', $row) {
       self::trunc($row['content'], 60);
    }
    

    要检查下标是否存在且不为空,请使用isset

    【讨论】:

    • 好建议,或者试试isset(通常更快)
    猜你喜欢
    • 2019-03-01
    • 1970-01-01
    • 2020-11-29
    • 2017-06-14
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    相关资源
    最近更新 更多