2012-10-25 30 views
0

這讓我很難過。我可以打印名爲$item_pages的數組,並正確輸出所有的鍵和值。但是,一旦這個數組在foreach中使用,它就會變成空的。這是數組的時候我的print_r在foreach之外:陣列在foreach時丟失值

Array ([0] => 1 [1] => 6 [2] => 12 [3] => 15 [4] => 16 [5] => 17 [6] => 18 [7] => 19 [8] => 78 [9] => 79 [10] => 87 [11] => 90 [12] => 94 [13] => 95 [14] => 98 [15] => 99 [16] => 102 [17] => 103 [18] => 105 [19] => 107 [20] => 108 [21] => 110 [22] => 111 [23] => 112 [24] => 113 [25] => 114 [26] => 119 [27] => 120 [28] => 121 [29] => 125 [30] => 126 [31] => 134 [32] => 135 [33] => 136 [34] => 138 [35] => 142 [36] => 186 [37] => 193 [38] => 197 [39] => 198 [40] => 199 [41] => 206 [42] => 327 [43] => 452 [44] => 470 [45] => 487 [46] => 601 [47] => 614 [48] => 630 [49] => 684 [50] => 726 [51] => 727 [52] => 789 [53] => 871) 

這裏的控制器:

public function view_item_pages() { 

    if ($this->input->is_ajax_request()) { 

     $item_id = $this->input->post('item_id'); 
     $this->data['item_id'] = $item_id; 
     $this->data['pages'] = $this->affiliate_model->get_all_affiliates(); 
     $this->data['item_pages'] = $this->item_model->get_item_pages($item_id); 

     $this->load->view('/admin/item/pages', $this->data); 

    } 

    } 

這裏的觀點:

<fieldset> 
    <table id="all-pages" class="table table-striped table-bordered"> 
     <thead> 
      <tr> 
      <th><input type="checkbox" class="checkbox" id="select_all"></th> 
      <th>ID</th> 
      <th>Name</th> 
      </tr> 
     </thead> 
     <tbody> 

     <?php foreach ($pages as $page): 

      $checked = FALSE; 

      if (!empty($item_pages)) { 
       if (in_array($page['aff_id'], $item_pages)) { 
        $checked = TRUE; 
       } 
      } 
     ?> 
       <tr> 
       <td><?php echo form_checkbox('page', $page['aff_id'], $checked); ?></td> 
       <td><?php echo $page['aff_id']; ?></td> 
       <td><?php echo $page['name']; ?></td> 
       </tr> 

     <?php endforeach; ?> 

     </tbody> 
    </table> 
</fieldset> 

所以,如果我這樣做,數組作品:

<?php print_r($item_pages); ?> 

    <?php foreach ($pages as $page): 

     $checked = FALSE; 

     if (!empty($item_pages)) { 
      if (in_array($page['aff_id'], $item_pages)) { 
       $checked = TRUE; 
      } 
     } 
    ?> 

如果我這樣做這一點,它不返回任何東西,這就像做echo '';

<?php foreach ($pages as $page): 

     print_r($item_pages); 

     $checked = FALSE; 

     if (!empty($item_pages)) { 
      if (in_array($page['aff_id'], $item_pages)) { 
       $checked = TRUE; 
      } 
     } 
    ?> 
+3

'$ pages'可能是空的 – air4x

+0

嘗試在'foreach'循環之外初始化它。 – andrewsi

+0

好的,如果您執行'print_r($ item_pages)'_after_'foreach'循環,會返回什麼? – raina77ow

回答

0

在你的控制器打印$pages。如果$pages爲空,則執行不會在視圖內進入foreach循環。

$this->data['pages'] = $this->affiliate_model->get_all_affiliates(); 
print_r($this->data['pages']); 
+0

是的,你說得對。不知道我是如何跳過這一點的。謝謝 – Motive