首页 > 解决方案 > 我在 PHP 5.6 中使用 PHP 7.1 中的 [] 创建了数组,给出了致命错误

问题描述

在 PHP 5.6 中这项工作正常,但在 PHP 7.1 中给出致命错误:未捕获错误:字符串不支持 [] 运算符

$result->execute();
$result->bind_result($id, $name);   
while($result->fetch()){
    $datos[]=array(
        $id => $name
    );
}

标签: phpmysql

解决方案


从 PHP 7.1 开始,当您访问像数组一样的非数组变量(在本例中为字符串)时,将引发致命错误。

首先初始化数组,使用$datos = [];. 这将覆盖您之前设置的任何内容,并将此变量显式设置为数组:

$result->execute();
$result->bind_result($id, $name);
$datos = [];
while($result->fetch()){
    $datos[]=array(
        $id => $name
    );
}

如果您尝试创建$id=>数组$name,则以下代码应该可以工作:

$result->execute();
$result->bind_result($id, $name);
$datos = [];
while($result->fetch()){
    $datos[ $id ] = $name;
}

推荐阅读