首页 > 解决方案 > 如何在 php 7 中的数组中使用追加数据

问题描述

我离开了 php,但我的代码有问题。并查看有很多区别 b/w php 5 n 7 所以看看这个

php 5

while ($result = $data->fetch(PDO::FETCH_OBJ))
{
   $res[]=$result;
}
return $res;

所以这会导致 php 7 中的错误

Fatal error: Uncaught Error: [] operator not supported for strings in /Applications/MAMP/htdocs/my/xxx/xxx/db.php:73 Stack trace: #0 /Applications/MAMP/htdocs/my/xxx/xxx/index.php(12): Database->show_all('admin') #1 {main} thrown in /Applications/MAMP/htdocs/xxx/xxx/xxx/db.php on line 73

你能告诉我如何用 php 7 写这个吗

标签: phparrayserror-handlingphp-7

解决方案


您可能定义$res

$res = '';

将其定义为字符串。

您需要确保将其初始化为数组以使用该[]方法...

$res = [];
while ($result = $data->fetch(PDO::FETCH_OBJ))
{
   $res[]=$result;
}
return $res;

推荐阅读