0

我是PHP和Zend Framework的新手。我遇到了錯誤:注意:undefined索引'itemid'在foreach構造中

Notice: Undefined index: itemid in C:\xampp\htdocs\blogshop\application\views\scripts\item\tops.phtml on line 58

我不明白爲什麼會出現此錯誤。

public function topsAction() //tops action 
{ 
    //$tops = new Application_Model_DbTable_Item(); 
    //$tops->getTops(); 
    $item = new Application_Model_DbTable_Item(); //create new Item object 
    $this->view->item = $item->getTops(); //$this->view->item is pass to index.phtml 
} 

這是我的控制器代碼。

public function getTops() 
{ 
    $row = $this->fetchAll('itemtype = "Tops"'); //find Row based on 'Tops' 
    if (!$row) { //if row can't be found 
     throw new Exception("Could not find Tops!"); //Catch exception where itemid is not found 
    } 
    return $row->toArray(); 
} 

這是我在模型中的getTops操作,以獲取數據庫中類別爲「Tops」的行。

<?php foreach($this->item as $item) : ?> 
    <?php echo $this->escape($this->item['itemid']);?> // This is where the error happens 
    <img src="<?php echo $this->escape($item->image);?>" width="82" height="100"> 
    <?php echo $this->escape($this->item['itemname']);?> 
    <?php echo $this->escape($this->item['description']);?> 
    <?php echo $this->escape($this->item['itemtype']);?> 
<?php endforeach; ?> 

這是我的代碼顯示所有我有我的數據庫中的行。

回答

2

您的$this->item陣列中沒有名爲itemid的索引,這就是爲什麼您會收到該錯誤。

此外,您的代碼在這裏似乎有點不對勁:

<?php foreach($this->item as $item) : ?> 
    <?php echo $this->escape($this->item['itemid']);?> 
    <img src="<?php echo $this->escape($item->image);?>" width="82" height="100"> 
    <?php echo $this->escape($this->item['itemname']);?> 
    <?php echo $this->escape($this->item['description']);?> 
    <?php echo $this->escape($this->item['itemtype']);?> 
<?php endforeach; ?> 

$this->itemforeach語句中應$item被替換爲迭代工作。所以它將是$item['itemid'],$item['itemname'],等等。你缺少一個更深層次的數組,使迭代foreach無用。

我猜$this->item看起來是這樣的:

array (
    1 => 
    array (
    'itemid' => 1, 
    'itemname' => 'foobar', 
), 
    2 => 
    array (
    'itemid' => 2, 
    'itemname' => 'bazqux', 
), 
) 

這就是爲什麼$this->item['itemid']回報任何東西,因爲它不存在。 $this->item[1]['itemid']但是確實是foreach週期可以幫助您做的是它遍歷(重複)整個$this->item陣列,每個值在內表示爲循環內部。在第一次運行中,$item$this->item[1],第二次爲$item$this->item[2],依此類推等等。

因此,將$this->item改爲$item內部的foreach構造。

+0

好的,它現在可以工作。非常感謝:) – 2012-08-08 12:16:44

+0

@SwapTest很高興能夠提供幫助。但是,請花點時間瞭解您正在使用和正在做的事情。 ([foreach]的相關手冊頁(http://php.net/manual/en/control-structures.foreach.php))我很高興告訴你該怎麼做,並且將我的_fix_合併到了你的文件中,但如果你不明白它爲什麼會起作用,那麼這樣做會產生價值。此外,如果這是一個很好的答案,請將它標記爲旁邊透明_tick_的答案,以便進一步的讀者會看到這個答案確實奏效。 – Whisperity 2012-08-08 12:24:17