php - 无法从循环中为数组赋值

标签 php mysql arrays function class

我有这个代码:

function retrieve_answers($array = array(), $id = null)
{
    include(root_path . '\config.php');
    if($id == null)
    {
        $id = $this->question_id;
    }
    $query = mysqli_query($link, "SELECT * FROM `answers` WHERE `question_id`='$id'");
    if(!mysqli_num_rows($query))
    {
        throw new Exception('Question not found.');
    }
    /* - Retrieves the answer rows
    - Loops through the array
    - Indexes the array and assigns the answerID to the index */
    else
    {
        while($result = mysqli_fetch_array($query))
        {
            for($i=0;$i<mysqli_num_rows($query);$i++) 
            {
                $array[$i] = $result["id"]; 
            }
        }
    }
}

这是一个类的一部分。

我想做什么? 我试图接受一个数组作为参数,并将值分配给该数组,这些值是链接到问题的answerID。

test.php 文件在这里:

<?php
define('root_path', realpath(dirname(__FILE__)));
include(root_path . '\config.php');
require_once(root_path . '\includes\question.class.php');

$q = new Question(3);

$array = array();

$q->retrieve_answers($array);

var_dump($array);
?>

会发生什么? 当我尝试通过转储数组进行调试时,它显示该数组不包含任何内容:

array(0) { }

我尝试通过类执行 MySQL 结果进行调试,并且它确实成功检索到答案 ID,因此我非常肯定问题出在数组中。

我很高兴获得帮助,提前致谢。

最佳答案

像这样的函数的返回值

function retrieve_answers($array = array(), $id = null)
{
    include(root_path . '\config.php');
    if($id == null)
    {
        $id = $this->question_id;
    }
    $query = mysqli_query($link, "SELECT * FROM `answers` WHERE `question_id`='$id'");
    if(!mysqli_num_rows($query))
    {
        throw new Exception('Question not found.');
    }
    /* - Retrieves the answer rows
    - Loops through the array
    - Indexes the array and assigns the answerID to the index */
    else
    {
        $i = 0;
        while($result = mysqli_fetch_array($query))
        {
            $array[$i] = $result["id"];                 
            $i++;
        }
    return $array;
    }


}

然后将其获取为

$arr = $q->retrieve_answers($array);

var_dump($arr);

关于php - 无法从循环中为数组赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30594335/

相关文章:

php - 如何将易受攻击的 SQL 查询转换为 PHP 参数化查询

php - 需要帮助从 mysql 数据填充下拉菜单

Java排序——全部大写优先

php - 使用 PHP 代码写入 PHP 文件?

php - xampp wordpress 虚拟主机 - css 错误,未应用 css

php - 在流明中找不到 'Redis'类

mysql - 带联接的MySQL表查询

mysql - 如何用tshark获取sql语句?

arrays - Swift通用数组函数查找不匹配项目的元素的所有索引

c# - 数组中的相等值