【问题标题】:How to iterate over an array of arrays如何遍历数组数组
【发布时间】:2011-10-30 02:31:26
【问题描述】:

希望有人能帮忙。

我确定这只是一个简单的问题,但由于某种原因我无法解决。

基本上我有一个类来处理我所有的数据库功能(连接、选择、插入、更新)。

在选择函数中我返回一个数组。

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', '', '', '', '');

在 for each 循环中(见下文)我只从数据库中获取结果的第一个字母。

 <?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
        }
    ?>

任何帮助都会很棒。

谢谢。

【问题讨论】:

    标签: php mysql arrays oop foreach


    【解决方案1】:

    替换:

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

    与:

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

    【讨论】:

      【解决方案2】:

      嗯,你的大问题是你试图遍历数组的 0 索引。

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

      这将使您真正获得一些合法的迭代,但还有一些其他的事情是您即将遇到的问题。

       // 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());

      当然,您应该在所有数据库输入上使用mysql_real_escape_string

      【讨论】:

        猜你喜欢
        • 2022-01-21
        • 1970-01-01
        • 2014-09-09
        • 2015-04-07
        • 1970-01-01
        • 2023-01-29
        • 1970-01-01
        相关资源
        最近更新 更多