2014-01-27 126 views
0

如何清除數組索引。 原因,如果我使用foreach我只得到[0]和[1] 或者我應該有機會的foreach代碼?清除數組索引

** SQL數據庫選擇。 **

$data = $rs->fetchAllAssoc(); 

**的陣列我得到當我使用的print_r ***

<pre><?php print_r ($this->data); ?></pre> 


Array 
    (
     [0] => Array 
      (
       [id] => 1 
       [pid] => 0 
       [sorting] => 0 
       [text] => text 
      ) 

     [1] => Array 
      (
       [id] => 2 
       [pid] => 0 
       [sorting] => 0 
       [text] => text 
      ) 
    ) 

**的PHP代碼我用它來獲得數據*

 <?php foreach ($this->data as $datafield): ?> 
      <td> 
      <?php echo $datafield; ?> 
      </td> 
     <?php endforeach; ?> 

* 而在頁面上我得到這個* Array Array

+0

迭代通過內部陣列呢? –

回答

0

如果你的print_r($數據字段),這是你會得到什麼:

Array 
      (
       [id] => 1 
       [pid] => 0 
       [sorting] => 0 
       [text] => text 
      ) 

Array 
      (
       [id] => 2 
       [pid] => 0 
       [sorting] => 0 
       [text] => text 
      ) 

這意味着你沒有迭代裏面陣列即$這個 - >數據[0],$ this-> data [1]

所以你應該有另一個內置的foreach循環遍歷$ datafield。

<?php foreach ($this->data as $datafield): ?> 
     <?php foreach($datafield as $key => $value): ?> 
      <td> 
      <?php echo $value; ?> 
      </td> 
      <?php endforeach; ?> 
<?php endforeach; ?> 

這會給你:

1 
0 
0 
text 
2 
0 
0 
text 
+0

Thx很多。 :) 是否可以清除一些項目? 如果不需要ID – user1551496

+0

當然是...使用unset($ datafield('id'));它將刪除該數組鍵值對。 :) –

0

你只是遍歷外部數組。

裏面應該有另一個循環。

<?php foreach ($this->data as $outerIndex => $array): ?> 
    <?php foreach($array as $innerIndex => $data): ?> 
     <td> 
      <?php echo $innerIndex; ?> 
     </td> 
    <?php endforeach; ?> 
<?php endforeach; ?> 
+0

哦thx這是完美的原因,現在我可以爲每個陣列單獨製作 – user1551496