PHP foreach MVC警告
我一直在努力学习一些PHP。我正试图打印出数据库的内容。我一直在遵循一个教程,但遇到了以下警告,我根本无法转换 警告PHP foreach MVC警告,php,model-view-controller,Php,Model View Controller,我一直在努力学习一些PHP。我正试图打印出数据库的内容。我一直在遵循一个教程,但遇到了以下警告,我根本无法转换 警告 Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/Lab10/app/views/View.php on line 20 Foreach循环 $HTMLItemList = ""; foreach ( $this->model->item
Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/Lab10/app/views/View.php on line 20
Foreach循环
$HTMLItemList = "";
foreach ( $this->model->itemList as $row )
$HTMLItemList .= "<li><strong>" . $row ["title"] . ": </strong>" . $row ["price"] . "<blockquote>" . $row ["description"] . "</blockquote></li>";
$HTMLItemList = "<ul>" . $HTMLItemList . "</ul>";
itemsDAO->getItems()
PHP试图在foreach上迭代的变量不是数组。尝试
var\u dump()
it进行检查
您可以将array()
设置为模型上itemList
属性的默认值,这样,如果未调用初始值设定项方法,foreach将不会发出警告
您在这里犯的错误是调用了getItems
方法,并将结果放在ItemList
属性上,而不是ItemList
。当心这个案子
替换
public function prepareItemList() {
$this->ItemList = $this->itemsDAO->getItems();
}
借
它会起作用的。请试试这个
$this->model->prepareItemList();
$HTMLItemList = "";
foreach ( $this->model->itemList as $row )
$HTMLItemList .= "<li><strong>" . $row ["title"] . ": </strong>" . $row ["price"] . "<blockquote>" . $row ["description"] . "</blockquote></li>";
您的项目列表为空或错误类型,您确定要在foreach之前调用prepareItemList(),并且项目列表是数组吗?上面的代码就是我一直在做的,我应该在foreach循环前几行调用prepareItemList()吗?是的,我想。在访问itemList之前必须调用prepareItemList(),您的型号名称是什么,您一直在调用
itemList
而不是prepareItemList
,而且您的代码中有很多打字错误您itemList
!=ItemList
感谢您的回复,但在更改后,我仍然会收到相同的错误在您的代码上添加一些var\u dump()
以了解发生了什么,我们无法为您调试。欢迎您。您必须首先调用prepare函数,然后使用itemList,否则itemList总是空的。
public function prepareItemList() {
$this->ItemList = $this->itemsDAO->getItems();
}
public function prepareItemList() {
$this->itemList = $this->itemsDAO->getItems();
}
$this->model->prepareItemList();
$HTMLItemList = "";
foreach ( $this->model->itemList as $row )
$HTMLItemList .= "<li><strong>" . $row ["title"] . ": </strong>" . $row ["price"] . "<blockquote>" . $row ["description"] . "</blockquote></li>";
public $itemList=null;
public function prepareItemList () {
$this->itemList = $this->itemsDAO->getItems ();
}