【问题标题】:how to use append data in an array in php 7如何在 php 7 中的数组中使用追加数据
【发布时间】:2018-12-08 14:17:12
【问题描述】:

我离开了 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 中写这个

【问题讨论】:

  • 您能否将您在 PHP 7 中遇到的错误添加到您的问题中。
  • 我编辑我的问题请检查
  • 如果$res 是一个字符串,那在php5中应该如何工作?它的目的是什么?

标签: php arrays error-handling php-7


【解决方案1】:

您可能将$res 定义为

$res = '';

将其定义为字符串。

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

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

【讨论】:

  • 我在你面前得到了答案,但你应该得到这个;)
【解决方案2】:

array_push() 可能是您正在寻找的解决方案

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

【讨论】:

    【解决方案3】:

    $res = [];而 ($result = $data->fetch(PDO::FETCH_OBJ)) { $res[]=$result; } 返回 $res;

    有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 2015-11-08
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      相关资源
      最近更新 更多