运行我的脚本时出现了一些错误:
警告:非法字符串偏移' photo_id'在第35行的/var/www/BrandonsBlog/comments.php中 注意:未定义的偏移量:第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()
中,由于某种原因,似乎每行中的值都是重复的,这可能导致我的错误?
答案 0 :(得分:1)
改变这个:
$photo_id = $value[$key]['photo_id'];
到此:
$photo_id = $value['photo_id'];
应该有效
答案 1 :(得分:1)
Foreach提供您不需要使用键值的直接数组值。
从以下foreach
中删除[$ key]foreach ($test2 as $key => $value) {
$photo_id = $value['photo_id'];
//echo '<div class="hello" id="'.$photo_id.'"></div>';
}