在while循环中更改id后添加新元素

时间:2013-01-16 08:20:52

标签: php mysql loops while-loop

我有while循环从mysql表中获取信息。但无法确定如何查找包含相同factor_id的las条目,并在其后添加追加新元素。

    if ($this->_db->numRows() > 0) {
        $i = 1;
        $j = '';
        $row = '';
        while ($row = mysqli_fetch_assoc($res_info)) {

            if ($row['task_factor_category'] != $j) {
                $title = '<tr><td colspan="4" class="title" style="text-align: left;">' . $row['task_factor_category'] . '</td></tr>';
                $comment = '<tr><td class="title" style="text-align: left" colspan="4">' . $this->_glan['comments'] . '</td></tr><tr><td colspan="4"><textarea cols="82" rows="3" name="factor_comment[' . $row['factor_id'] . ']" id="' . $row['factor_id'] . '"></textarea></td></tr>';
            } else {
                $title = false;
                $comment = false;
            }
            $this->reg['edit_fields']['factors'] .= $title . '<tr>
        <td>
        ' . $row['factors'] . '
        </td>
        <td>
        <input type="radio" name="task_factor[' . $i . '_' . $row['factor_id'] . ']" value="1"  />
        </td>
        <td>
        <input type="radio" name="task_factor[' . $i . '_' . $row['factor_id'] . ']" value="2" checked />
        </td>
        <td>
        <input type="radio" name="task_factor[' . $i . '_' . $row['factor_id'] . ']" value="3" />
        </td>
        </tr>
        ';
            $j = $row['task_factor_category'];
            $i++;
        }
    }

输出如下:

         //results with $row['factor_id'] = 10;
title
    1. entry
    2. entry
    3. entry
    4. entry
    5. entry
  //need new element here

  //results with $row['factor_id'] = 11;
 title
    1. entry
    2. entry
    3. entry
    4. entry
    5. entry
   //need new element here

    ......

我需要在包含相同因子ID

的最后一个条目之后添加其他元素

2 个答案:

答案 0 :(得分:0)

你可能想试试这个。

$id = array();
$i = 0;

while ($row = mysqli_fetch_assoc($res_info))
{
    $id[$i] = $row['id'];

    if ($i != 0 && $id[$i-1] != $row['id']) {
        //new element
    } else {
        //same element
    }
    $i++
}

答案 1 :(得分:0)

你可以计算总行数,假设有7行

在while循环中添加if代码,如

while(cond)
{
    if($i == 7 )
    {
      then echo("what ever you want");
    }
}