Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP foreach MVC警告_Php_Model View Controller - Fatal编程技术网

PHP foreach MVC警告

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

我一直在努力学习一些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->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 ();
}