PHP(codeigniter) - 如何检查下两行是否有值?

时间:2016-05-10 07:46:37

标签: php html sql codeigniter

我想检查下一个两个行或 ID 不是NULL

因为如果没有成功的两个行或 ID ,那么收入将保持为零。

        foreach ($data as $row)
        {
          if(($row->id + 2) != NULL) //I don't know what is the correct statement here
          {
            echo "<tr>";
            echo "<td>".$row->id."</td>"; 
            echo "<td>".$row->username."</td>"; 
            echo "<td>"."650.00"."</td>"; 
            echo "<td>".$row->remarks."</td>"; 
            echo "<tr>";
          }
          else
          {
            echo "<tr>";
            echo "<td>".$row->id."</td>"; 
            echo "<td>".$row->username."</td>"; 
            echo "<td>".$row->income."</td>"; 
            echo "<td>".$row->remarks."</td>"; 
            echo "<tr>"; 
          }                  
        }

这是我想要实现的表格。

==================================
|ID | Username | Income | Remarks|
| 2 | user1    | 650.00 |        |
| 3 | user2    | 650.00 |        |
| 4 | user3    |   0.00 |        |
| 5 | user4    |   0.00 |        |
==================================

如果我添加用户名,则下一个输出将是:

==================================
|ID | Username | Income | Remarks|
| 2 | user1    | 650.00 |        |
| 3 | user2    | 650.00 |        |
| 4 | user3    | 650.00 |        |
| 5 | user4    |   0.00 |        |
| 6 | user5    |   0.00 |        |
==================================

2 个答案:

答案 0 :(得分:1)

您需要更改foreach以获取索引。

    foreach ($data as $index => $row)

然后,您可以通过以下方式处理与当前行相关的所有行:

    $row_two_ahead = $data[$index + 2];

您应该在尝试使用该行之前检查该行是否存在,否则您将获得超出范围异常的索引:

    if (isset($data[$index + 2])) {
    }

答案 1 :(得分:0)

我解决了这个问题...

这是我控制器的代码:

public function addUsername()
{
  $data['id'] = NULL;
  $data['username'] = $this->input->post('username');
  $data['reward'] = 0.00;
  $data['remarks'] = ' ';

  $this->Matrix_model->addUsername($data);
  $last = $this->Matrix_model->getLast();
  $index = $last - 2; //I minus the last index with two
  $this->Matrix_model->updateIncome($index); //and updated the income of that index
  redirect('http://localhost/matrix/index.php/matrix');
}

这是我模特的代码:

public function addUsername($data)
   {
    $this->db->insert("income", $data);
   }

public function getLast()
  {
    return $this->db->insert_id(); //this is the method to access the last id inserted
  }

public function updateIncome($id)
  {
     $this->db->set("reward", 650);
     $this->db->where("id", $id); 
     $this->db->update("income"); 
  }

谢谢,如果其他程序员不理解我的问题,我很抱歉