PHP 注意:数组到字符串转换错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18759096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:10:37  来源:igfitidea点击:

PHP Notice: Array to string conversion Error

php

提问by ngplayground

Been experiencing this error for a little while and can't find any conclusive answers on fixing it. I have tried removing quotes from $keyin line 59 but to no avail.

已经遇到这个错误一段时间了,但找不到修复它的任何结论性答案。我曾尝试从$key第 59 行中删除引号,但无济于事。

if (!get_magic_quotes_gpc()) {
    if (isset($_POST)) {
        foreach ($_POST as $key => $value) {
            $_POST['$key'] =  trim(addslashes($value));
        }
    }

    if (isset($_GET)) {
        foreach ($_GET as $key => $value) {
            $_GET[$key] = trim(addslashes($value));
        }
    }   
}

LINE 59

第 59 行

$_POST['$key'] =  trim(addslashes($value));

Error On Screen

屏幕上的错误

Notice: Array to string conversion in C:\Inetpub\vhosts\domain.com\httpdocs\library\config.php on line 59

注意:C:\Inetpub\vhosts\domain.com\httpdocs\library\config.php 中第 59 行的数组到字符串的转换

采纳答案by Starx

Check if it is array before you assign it

在分配之前检查它是否是数组

$_POST[$key] =  !is_array($value) ? trim(addslashes($value)) : '';
   //  ^   Remove the quotes here                          //  ^ Do something 
                                                           //  Instead of 
                                                           //  Using empty

回答by vanurag

I think you should use this code $_POST[$key] = $value;instead of using this $_POST['$key'] = trim(addslashes($value));

我认为您应该使用此代码$_POST[$key] = $value;而不是使用此$_POST['$key'] = trim(addslashes($value));

or make a check if the value is in array or not

或检查该值是否在数组中

回答by David 'the bald ginger'

According to PHP.netthe function addslashes() takes a String type as parameter. Check what type $value is. If it is an array itself then addslashes() may be throwing the error.

根据PHP.net,函数addslashes() 将字符串类型作为参数。检查 $value 是什么类型。如果它是一个数组本身,那么addslashes() 可能会抛出错误。

PS: You should use $_POST[$key] rather than $_POST['$key'] if you want to use the value of $key as the index of the $_POST array.

PS:如果你想使用 $key 的值作为 $_POST 数组的索引,你应该使用 $_POST[$key] 而不是 $_POST['$key'] 。

回答by Barmar

Do this:

做这个:

foreach ($_POST as &$value) {
    $value = is_array($value) ?
        array_map(function($x) { return trim(addslashes($x)); } :
        trim(addslashes($value));
}

However, this could still fail if any of your parameters are multi-dimensional arrays. As mentioned in the comments, the right solution is to use prepared queries with parameters, rather than interpolating strings into SQL.

但是,如果您的任何参数是多维数组,这仍然可能会失败。正如评论中提到的,正确的解决方案是使用带参数的准备好的查询,而不是将字符串插入到 SQL 中。