【问题标题】:Iterating through a recordset when returned as an array by a function当函数作为数组返回时遍历记录集
【发布时间】:2017-08-06 11:33:57
【问题描述】:

如何遍历从 PHP 函数返回的数组 Object 以检索记录集的所有记录?

试图让这段代码返回一个包含所有行的数组

 // @param group_id @returns result rows of all post from group with the corresponding ID

        function getGroupPostItem($group_id){

      $sql_query = mysql_query("SELECT * FROM posts WHERE gid = '$group_id'");
   while( $rows = mysql_fetch_assoc($sql_query)) {



$record_set = array('gid' => $rows['gid'],
                    'pid' => $rows['pid'],
                    'post' => $rows['post'],
                    'filemap_id' => $rows['filemap_id']);


return $record_set;



       }
            }

尝试使用下面的代码打印数据库中与查询匹配的行中的所有记录,但它所做的只是打印一行。

$arr = getGroupPostItem('6');
echo $arr['post']. '<br/>' ;

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    你应该可以改变这一行:

    $record_set = array('gid' => $rows['gid'],
    

    ...到这个:

    $record_set[] = array('gid' => $rows['gid'],
    

    编辑:另外,正如 Paul T 的评论所述,return $record_set; 应该在 while 循环之外。

    注意:echo $arr['post'] . '&lt;br/&gt;'; 单独不会显示单个值,因为它现在是一个数组。相反,它必须通过 for 或 foreach 循环。示例:

    foreach ($arr as $val) {
      echo $val['post'] . '<br/>';
    }
    

    ... 或:

    for ($i = 0; $i < count($arr); $i++) {
      // Optional, if you want the loop to stop at the 0th value
      if ($i == 0) {
        echo $arr[$i]['post'] . '<br/>';
      }
    }
    

    【讨论】:

    • ...return $record_set; 应该在 while 循环之外?
    • 不断抛出未定义的索引错误!不锻炼
    • @Maxwell: ...函数返回后,添加一个var_dump($arr);,这样就可以看到数组信息是怎么出现的了。
    猜你喜欢
    • 1970-01-01
    • 2011-08-13
    • 2019-12-16
    • 2013-09-28
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    相关资源
    最近更新 更多