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

时间:2011-10-19 00:23:22

标签: php mysql arrays if-statement while-loop

抱歉,我不得不再次提交此问题,因为我几乎没有任何意见,因为这是一个旧帖子。我很绝望,但要回答这个问题。请帮帮我。

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

例如:$ row ['Answercontent'] =利兹(这是问题的正确答案。)$ row ['StudentAnswer'] =利兹(这是学生为答案提出的答案。)$ row ['weight%']是正确答案的标记百分比。让我们说上面例子的答案=总分数的5%。现在,上面的例子显示学生的答案与正确的答案相匹配,这意味着在我想要创建的新字段中(让我们调用它($ row ['StudentAnswerWeight'])来显示答案的百分比百分比如果学生把答案弄错了,那么学生会把他/她的答案变成'曼彻斯特'。学生的体重应该= 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>";
    }
  ?>

谢谢

2 个答案:

答案 0 :(得分:1)

echo

之前添加此内容
if ( $row['StudentAnswer'] == $row['AnswerContent'] ) {
  $row['StudentAnswerWeight'] = $row['Weight%'];
} else {
  $row['StudentAnswerWeight'] = '0';
}

摆脱这个{$row['StudentAnswer'] = $row['AnswerContent']}

答案 1 :(得分:1)

试试这个:echo ($row['StudentAnswer']==$row['AnswerContent']) ? $row['Weight%'] : '0'

在你的例子中

<?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>";
echo ($row['StudentAnswer']==$row['AnswerContent']) ? $row['Weight%'] : '0';
echo "</td><td>{$row['StudentId']}</td>
  </tr>";
    }
  ?>