2011-08-18 88 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

感谢您的帮助。不能相信我没有尝试过。 –