php - 如何在数组中创建一个新字段?

标签 php mysql arrays if-statement while-loop

抱歉,我不得不再次提交这个问题,因为这是一篇旧帖子,我几乎没有任何观点。但我很渴望得到答案。请帮助我。

我有一个将从数据库中获取行的数组。但我想要做的是在表中创建一个新的空行,其中如果 $row['StudentAnswer'] 等于 $row['AnswerContent'] 则新字段(假设它称为 $row['StudentAnswerWeight'])= $row['Weight%'] else $row['StudentAnswerWeight'] = '0'。

例如:$row['Answercontent'] = Leeds(这是问题的正确答案。) $row['StudentAnswer'] = Leeds(这是学生给出的答案。)$ row['weight%'] 是正确答案分数的百分比。假设上例的答案 = 总分的 5%。现在,如上面的示例所示,学生的答案与正确答案相匹配,这意味着在我想要创建的新字段中(让我们称其为 ($row['StudentAnswerWeight']) 来显示答案的 wieght% 百分比是 5%。如果学生网络的答案错误,可以说学生输入了他/她的答案“曼彻斯特”。学生答案权重应该 = 0%,因为答案是错误的。我希望您现在明白我想要实现的目标。

我们不能创建一个新的 $row['...']($row['StudentAnswerWeight' 是新的 $row['...'] 将被调用的内容)并使用 if 语句吗?如果 $row['AnswerContent'] = $row['StudentAnswer'] 则 $row['...'] = $row['Weight%'] 否则 $row['...'] = '0'。我正在沿着这些思路思考,但我无法让它发挥作用,我希望你们能弄清楚:)

下面是php代码中的数组和表中的字段:

<table border='1'>
  <tr>
  <th>Session ID</th>
  <th>Question Number</th>
  <th>Question</th>
  <th>Correct Answer</th>
  <th>StudentAnswer</th>
  <th>Correct Answer Weight</th>
  <th>Student Answer Weight</th>
  <th>Student ID</th>
  </tr>
  <?php

    while ($row = mysql_fetch_array($result)) {
            echo "
  <tr>
  <td>{$row['SessionId']}</td>
  <td>{$row['QuestionNo']}</td>
  <td>{$row['QuestionContent']}</td>
  <td>{$row['AnswerContent']}</td>
  <td>{$row['StudentAnswer']} </td>
  <td>{$row['Weight%']}</td>
  <td>{$row['StudentAnswer'] = $row['AnswerContent']}</td> 
  <td>{$row['StudentId']}</td>
  </tr>";
    }
  ?>

谢谢

最佳答案

echo之前添加此内容:

if ( $row['StudentAnswer'] == $row['AnswerContent'] ) {
  $row['StudentAnswerWeight'] = $row['Weight%'];
} else {
  $row['StudentAnswerWeight'] = '0';
}

并去掉这个{$row['StudentAnswer'] = $row['AnswerContent']}

关于php - 如何在数组中创建一个新字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7815271/

相关文章:

php - 想要通过加入交货来填充销售表中的记录集

mysql - 使用 VB.net 更改 gridview 的列名称

javascript - .split 通过将字符串转换为数组返回 NaN

php - 将运行用户从 nt authority\system 更改为 AD 用户 - Windows 上的 Apache

PHP $_POST 多行数组

php - 如何计算两个日期之间的月数

JavaScript循环错误: Uncaught TypeError

mysql - 如何在 mysql 中使用 'where' 写入 'am' 条件。

php - MySql:在子查询中引用父查询获取的数组

python - 将列表中的元素分配给数组