未能值在循环分配到数组 [英] Failing to assign values to array from a loop

查看:154
本文介绍了未能值在循环分配到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个code:

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"]; 
            }
        }
    }
}

这是一个类的一部分。

Which is a part of a class.

什么是我想要做什么?
我想接受一个数组作为参数,并分配值数组,值其链接到的问题是answerIDs。

What am I trying to do? I am trying to accept an array as a parameter, and assign values to the array, the values are to be answerIDs which are linked to the question.

该文件test.php的是在这里:

The test.php file is here:

<?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);
?>

会发生什么?
当我尝试倾销阵列进行调试,这表明该数组包含什么:

What happens? When I try to debug by dumping the array, it shows that the array contains nothing:

阵列(0){}

我试图执行MySQL的通过类来调试的结果,它确实成功获取答案的ID,所以我pretty正面的问题是阵列中的

I tried to execute the MySQL result through the class to debug, and it does succeed to retrieve the answer IDs, so I'm pretty positive the issue is in the array.

我会高兴地得到帮助,在此先感谢。

I would happy to get assistance, thanks in advance.

推荐答案

在这样的函数返回值

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

这篇关于未能值在循环分配到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆