致命错误:无法将stdClass类型的对象用作数据库项数组中的数组


Fatal error: Cannot use object of type stdClass as array from array with db items

我正试图以在我的网站上多次读取数组的方式读取数组。这一个给了我致命的错误:不能将stdClass类型的对象用作数组。在我的课堂上,我有:

public $productlist = array();
//GetFeatured 
while($obj = $result->fetch_object()){
$this->productlist[] = $obj;
}

在我的页面中,我试图显示它:

$prod = new product;
$prod->GetFeatured();
for($ind = 0; $ind <= count($prod->productlist) - 1; $ind++){
echo $prod->productlist[$ind]['productid'];
}

这会填充数组,但我不确定为什么会出现此错误。非常感谢您的帮助。

您在这里作为对象获取:

while($obj = $result->fetch_object()){

然后尝试访问这里的数组:

echo $prod->productlist[$ind]['productid'];

这样试试:

echo $prod->productlist[$ind]->productid;

另一种方法是在fetch_object 的位置使用fetch_assoc

while($obj = $result->fetch_assoc()){

然后它保持这样:

echo $prod->productlist[$ind]['productid'];

如果你想从数组风格的对象中获取数据,你的类需要实现ArrayAccess接口