2012-04-26 29 views
0

在我看來,我希望有一個HTML表是這樣的:CakePHP的2.1.1的foreach

 COUNTRY   TOWN 
     france   paris 

這是我的查詢:

$foo=$this->country->find('all', array(
    'contain' => array(
      'Town' => array(
       'conditions' => array("Town.country_id = country.id"), 
       'fields' => array('id','name') 
      ) 
     ) 
    ) 
); 

我要顯示我的看法是這樣的:

line6  <?php foreach ($diponibilite as $f): ?> 
line7 
line8   <tr> 
line9    <td><?php echo $f['country']['name'];?></td> 
line10    <td><?php echo $f['town']['name'];?></td> 
line11   
line12   </tr> 
line13  <?php endforeach; ?> 

該機型 '國家' 和 '城鎮' 相關聯:

country hasmany town and town belongsto country 

不幸的是,一個錯誤:

Notice (8): Undefined index: name [APP\View\index\index.ctp, line 10]

爲什麼?

+0

讓我們從基本的調試開始吧。將'debug($ f);'添加到循環內部的視圖中。它有'name'鍵嗎? – JJJ 2012-04-27 06:40:28

+0

嗨Juhana!謝謝你的評論。我做了你的建議:加調試($ F)的循環內的觀點,這是內容:「陣列( \t '國家'=>陣列( \t \t '身份證'=> '1', \t \t '名稱'=> '法國' \t) \t '鎮'=>數組( \t \t(INT)0 =>數組( \t \t \t 'ID'=> '1', \t \t \t「 name'=>'paris', \t \t \t 'COUNTRY_ID'=> '1' \t \t) \t \t(INT)1 =>數組( \t \t \t 'ID'=> '2', \t \t \t '名稱'=> '馬賽' , \t \t \t 'COUNTRY_ID'=> '1' \t \t) \t) )」我得到同樣的錯誤。我想我不使用正確的語法來查找foreach()的數組中的值????謝謝! – John 2012-04-27 08:29:36

回答

2

問題是,由於你有一個Country hasmany Town關係,可能在一個國家有多個城鎮(如debug($f)的輸出所示)。

要打印的所有城鎮,你需要另一個循環:

<?php foreach($diponibilite as $f): ?> 
    <tr> 
     <td><?php echo $f[ 'country' ][ 'name' ]; ?></td> 
     <td><?php 
      foreach($f[ 'town' ] as $town) { 
       echo $town[ 'name' ].' '; 
      } 
     ?></td> 
    </tr> 
<?php endforeach; ?> 

或者,如果你只是想第一個,使用$f[ 'town' ][ 0 ][ 'name' ]

備註:如果您已正確設置關聯,則不需要查找中的條件。你可以做

$foo = $this->country->find('all', array(
    'contain' => array(
      'Town.id', 
      'Town.name' 
     ) 
    ) 
); 
+0

非常感謝Juhana!按照你的建議,我的錯誤消失了!這是我的代碼:
'

' ' \t​​國家 \t \t​​鎮' '?' ' '' '​​<?php echo $ f ['country'] ['name']; ?>'' ​​'' '' ' '<?php endforeach; ?>'' '
和視圖顯示是這樣的: 鄉村小鎮 法國巴黎 法國馬賽 再次感謝Juhana! – John 2012-04-27 10:47:39