我在运行脚本时遇到了几个错误:
警告:第35行/var/www/BrandonsBlog/comments.php中的非法字符串偏移量"photo_id"
注意:未定义的偏移量:2 in/var/www/BrandonsBlog/comments.php on line 35
我的代码:
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()
中,每行中的值似乎都是重复的,这可能是我的错误的原因?
Foreach直接给出数组值,而不需要使用键值。
从下面的每个中删除[$key]
foreach ($test2 as $key => $value) {
$photo_id = $value['photo_id'];
//echo '<div class="hello" id="'.$photo_id.'"></div>';
}
更改此项:
$photo_id = $value[$key]['photo_id'];
到此:
$photo_id = $value['photo_id'];
应该工作