2011-08-18 104 views
1

我希望有人可以提供幫助。如何遍歷數組數組

我敢肯定,它只是一個簡單的,我只是不能出於某種原因出。

基本上我有:處理那些我所有的數據庫功能(連接,選擇,插入,更新)的一類。

在選擇功能,我返回一個數組。

public function getAll($table, $cols, $where, $limit, $order) { 
    // Set the query variables 
    if($cols == '') { 
     $cols = '*'; 
    } 
    if($where!='') { 
     $where = ' WHERE '.$where; 
    } 
    if($limit!= '') { 
     $limit = ' LIMIT '.$limit; 
    } 
    if($order!='') { 
     $order = ' ORDER BY '.$order; 
    } 

    // Make the query string 
    $sql = 'SELECT '.$cols.' FROM '.$table.$where.$order.$limit; 

    //echo $sql; 

    // Set the query 
    $news_qry = mysql_query($sql); 

    // Set the array 
    $rows = array(); 

    // Run a loop through the results 
    while($item = mysql_fetch_object($news_qry)) 
    { 
     // Add each row to an array. 
     $rows[] = $item; 
    } 
    return $rows;  
} 

此函數正在工作,因爲我可以打印數組。請看下圖:

Array ([Gallery_id] => 1 [Gallery_Name] => Test [Gallery_FolderName] => Test Folder) 

但是當我去使用對象 -

$arr_GalleryInfo = $dataObj->getAll('tbl_Gallery', '', '', '', ''); 

內每個循環(見下文),我只從數據庫中獲取結果的第一個字母。

<?php 
     foreach ($arr_GalleryInfo[0] as $arrGallery) 
     { 
    ?> 
      <tr> 
       <td> 
        <?php echo $arrGallery['Gallery_Name']; ?>   
       </td> 

       <td> 
        <?php echo $arrGallery; ?> 
       </td> 

       <td> 
        <?php echo $arrGallery; ?>  
       </td> 
      </tr> 
    <?php 
     } 
    ?> 

任何幫助將是偉大的。

謝謝。

回答

9

替換:

foreach ($arr_GalleryInfo[0] as $arrGallery) 
{ 
    etc... 

有:

foreach ($arr_GalleryInfo as $arrGallery)   
{ 
    etc...
1

好了,你的大問題是,你要遍歷數組的0指數。

foreach ($arr_GalleryInfo[0] as $arrGallery) // get rid of the `[0]`. 

這將使這樣你實際上得到一些合法的iteraction,但也有一些其他的事情是,你是要撞上陷阱。

// this will output `Array`. You want $artGallery['Gallery_FolderName'] 
// or $artGallery['Gallery_id'] 
echo $arrGallery; 

當然,你能避免整個第二個問題嵌套循環:

foreach ($arr_GalleryInfo as $arrGallery) { 
    echo '<tr>'; 
    foreach($arrGallery as $val) echo "<td>$val</td>"; 
    echo '</tr>'; 
} 

如果$news_qry = mysql_query($sql);失敗,你就會有什麼,如果東西壞了,提醒你。你應該這樣做:$news_qry = mysql_query($sql) or die(mysql_error());

而且,當然,你應該在所有的db輸入上使用mysql_real_escape_string

+0

感謝您的幫助。不能相信我沒有嘗試過。 –