繁体   English   中英

非法字符串偏移错误

[英]Illegal string offset error

我在运行脚本时遇到了一些错误:

警告:第35行/var/www/BrandonsBlog/comments.php中的非法字符串偏移'photo_id'
注意:未定义的偏移量:第35行的/var/www/BrandonsBlog/comments.php中为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()似乎每行中的值由于某种原因重复可能这导致我的错误?

改变这个:

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

对此:

$photo_id = $value['photo_id'];

应该管用

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM