PHP foreach循环中的“非法字符串偏移" [英] PHP 'Illegal string offset' in foreach loop

查看:93
本文介绍了PHP foreach循环中的“非法字符串偏移"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PDO从MySQL数据库中获得一个assoc阵列.

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

警告:C:\ www \ mvc \ libs \ Words.php中的字符串偏移量'content'非法14

Warning: Illegal string offset 'content' in C:\www\mvc\libs\Words.php on line 14

注意:未初始化的字符串偏移量:0,位于C:\ www \ mvc \ libs \ Words.php中第14行

Notice: Uninitialized string offset: 0 in C:\www\mvc\libs\Words.php on line 14

警告:C:\ www \ mvc \ libs \ Words.php中的非法字符串偏移量'content'在第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;
    }
}

推荐答案

这是因为内容不是 $ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆