我有这个代码:
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/