【问题标题】:Illegal string offset error非法字符串偏移错误
【发布时间】:2013-11-19 14:41:33
【问题描述】:

我在运行我的脚本时遇到了几个错误:

警告:第 35 行 /var/www/BrandonsBlog/cmets.php 中的非法字符串偏移量“photo_id”
注意:未定义的偏移量:/var/www/BrandonsBlog/cmets.php 第 35 行中的 2

我的代码:

    ini_set("display_errors", TRUE);
    include "Database.php";

    Class Database {
        protected $conn;

        public function setDb($conn){
            $this->conn = $conn;
        }
    }

    Class Images extends Database{
        protected $stmt;

        public function RetrieveImages(){

            $this->stmt = $this->conn->prepare('SELECT * FROM `pictures`');
            $this->stmt->execute();
            $boom = $this->stmt->fetchAll();
            return $boom;
        }
    }

    Class Content extends Images{

    }

    $test = new Images();
    $test->setDb($conn);
    $test2 = $test->RetrieveImages();

    var_dump($test2);
foreach ($test2 as $key => $value) {
    $photo_id = $value[$key]['photo_id'];
    //echo '<div class="hello" id="'.$photo_id.'"></div>';
}

var_dump($test2); 给了我以下输出:

array(3) {
  [0]=>;
  array(4) {
    ["id"]=>;
    string(1) "1"
    [0]=>;
    string(1) "1"
    ["photo_id"]=>;
    string(1) "1"
    [1]=>;
    string(1) "1"
  }
  [1]=>;
  array(4) {
    ["id"]=>;
    string(1) "2"
    [0]=>;
    string(1) "2"
    ["photo_id"]=>;
    string(1) "2"
    [1]=>;
    string(1) "2"
  }
  [2]=>;
  array(4) {
    ["id"]=>;
    string(1) "3"
    [0]=>;
    string(1) "3"
    ["photo_id"]=>;
    string(1) "3"
    [1]=>;
    string(1) "3"
  }
}

这是我从中检索的数据库表的样子:

mysql> select * from pictures;
+----+----------+
| id | photo_id |
+----+----------+
|  1 | 1        |
|  2 | 2        |
|  3 | 3        |
+----+----------+
3 rows in set (0.00 sec)

谁能告诉我为什么会收到此错误,并且在我的var_dump() 中似乎每行中的值由于某种原因重复,也许这导致了我的错误?

【问题讨论】:

  • 你的错误很清楚。它为您提供完整的信息。字符串索引不能是任何东西,而是非负整数。您的错误包含信息 - 它是哪一行,因此请使用 var_dump() 找出您的索引为何非法

标签: php


【解决方案1】:

Foreach 直接给出你不需要使用键值获取的数组值。

从下面的 foreach 中删除 [$key]

foreach ($test2 as $key => $value) {
    $photo_id = $value['photo_id'];
    //echo '<div class="hello" id="'.$photo_id.'"></div>';
}

【讨论】:

    【解决方案2】:

    改变这个:

    $photo_id = $value[$key]['photo_id'];
    

    到这里:

    $photo_id = $value['photo_id'];
    

    应该有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 2020-11-29
      • 2017-09-13
      • 1970-01-01
      相关资源
      最近更新 更多