PHP foreach无法正常工作

时间:2013-01-29 09:10:23

标签: php mysql sql arrays foreach

我在以下代码中遇到了一些问题......基本上,需要将几个值存储在 $ sqlBAnswer 中,但如果我只是将 [] 之后,它会保存值“数组”

//Find the answer given by the user to the last answered question
$sqlB = mysql_query("SELECT Answer FROM Responses WHERE User = $sqlAPKID");
//If the operation produces an error, output an error message
if (!$sqlB) {
    die('Invalid query for SQLB: ' . mysql_error());
}
//Count the number of rows output
$sqlBCount = mysql_num_rows($sqlB);
//If rows exist, define the values
if ($sqlBCount > 0) {
    while ($row = mysql_fetch_array($sqlB)) {
        $sqlBAnswer = $row["Answer"];
    }
}

假设 $ sqlBAnswer 确实设法保存了多个值,那么我需要执行另一个只生成一个值的查询(即只有一个值存储在 $ sqlBAnswer 将在结果集中。

我计划使用围绕以下代码的 foreach 循环执行此操作:

//Find the number of the next question to be answered based on the user's previous answer and the question they answered
$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $sqlBAnswer");
//If the operation produces an error, output an error message
if (!$sqlC) {
    die('Invalid query for SQLC: ' . mysql_error());
}
//Count the number of rows output
$sqlCCount = mysql_num_rows($sqlC);
//If rows exist, define the values
if ($sqlCCount > 0) {
    while ($row = mysql_fetch_array($sqlC)) {
        $sqlCNextQuestion = $row["NextQuestion"];
    }
}

我最后需要的是一个值和一个仅用于 sqlCNextQuestion 的值,但是我无法理解键和值等等,无论我阅读多少文档。如果有人能解释并告诉我如何实现我所追求的目标,我将非常感激!

谢谢:)

2 个答案:

答案 0 :(得分:3)

在您的代码中,$ sqlBAnswer不是一个数组,而只是一个普通变量。 你的代码:

if ($sqlBCount > 0) {
    while ($row = mysql_fetch_array($sqlB)) {
        $sqlBAnswer = $row["Answer"];
    }
}

简单地遍历查询结果中的行,并在每行中将$ row [“Answer”]的值重新分配给$ sqlBAnswer。

如果要将这些值保存到数组中,只需执行以下操作:

$sqlBAnswer = array(); //that creates a blank array to assign values to
if ($sqlBCount > 0) {
    while ($row = mysql_fetch_array($sqlB)) {
        $sqlBAnswer[] = $row["Answer"]; //note the '[]', which tells php to add the new value to the array
    }
}

然后您可以通过以下方式进行预告:

foreach($sqlBAnswer as $value){
    // use your code with $sqlBAnswer substituted by $value
}

但是 - 至于你将如何选择你想要的$ sqlCAnswer的值,你还没有充分描述你想要我完全回答的问题。这段代码将循环遍历$ sqlBAnswer的所有值,并可能生成$ sqlCAnswer的许多值(取决于您的数据库) - 因此您需要优化您的问题或自己弄清楚如何解决该问题。

答案 1 :(得分:0)

问题1的解决方案

$sqlBAnswer = $row["Answer"];

应该是

$sqlBAnswer[] = $row["Answer"];

我知道你提到它只存储“数组”。但事实并非如此,只是你在这里错误地访问它就会正确创建数组

$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $sqlBAnswer");  // No index being provided for array access

在你提到的foreach中,这将如下所示

foreach($sqlBAnswer as $ans)
{
$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $ans");
}