在 PHP 5.6 中,这工作正常,但在 PHP 7.1 中,它给出了致命错误:未捕获错误:字符串不支持 [] 运算符
$result->execute();
$result->bind_result($id, $name);
while($result->fetch()){
$datos[]=array(
$id => $name
);
}
从 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;
}