0

我正在使用 CodeIgniter 并想在循环中从对象中删除一个项目

foreach($query->result() as $row){
     if($row->parent_id == 1){
         // code here to delete current record
    }
}

我想使用 foreach 循环所有记录。如果循环中的当前项满足 if 中的条件,则删除 $query 对象中的当前行。

我可以在 CodeIgniter 中删除 $query 对象中的当前记录还是有其他方法可以做到这一点?

4

2 回答 2

4

在循环中从对象中删除项目

$query = $this->db->query("YOUR QUERY");
$rows = $query->result();
foreach ($rows as $key => $row)
{
  if($row->parent_id == 1){
      unset($rows[$key]);
     // code here to delete current record
  }
}

print_r($rows) // remove row with parent_id = 1

查看更多@Removing an item from object in a loop

您还可以更改您的 select 语句以获取 parent_id 不是 eq 1 的所有记录(或其他“where”逻辑来过滤行......请参见下面的示例和链接)

$this->db->get('mytable')
$this->db->where('parent_id !=', 1);

或者

//get all except parent id 1,4 or 7
$parent_ids = array(1, 4, 7);
$this->db->where_not_in('parent_id', $parent_ids);

从数据库中删除记录作为您之前的问题标题建议(在 CodeIgniter 中使用 foreach 删除当前记录)

您可以通过在 sql 中编写条件来使用 sql 查询而不使用任何 php 逻辑来执行此操作...在http://codeigniter.com/user_guide/database/active_record.html中查看更多信息

例子

//delete record where parent_id = 1
$this->db->delete('mytable', array('parent_id' => 1));

或者

//delete record where parent_id = 1 or 5 or 8
$names = array(1, 5, 8);
$this->db->where_in('parent_id', $names);
$this->db->delete('mytable');

或者

//delete record where parent_id = 1
$this->db->where('parent_id', 1);
$this->db->delete('mytable'); 

或者

//delete all record where parent_id not eq 1
$this->db->where('parent_id !=', 1);

//delete all record where parent_id less than 10
$this->db->where('parent_id <', 10); 
于 2012-10-26T04:50:56.433 回答
1

进行反转并将其添加到新数组中:

$new_result = array();

foreach($query->result() as $row){
    if($row->parent_id != 1){
       $new_result[] = $row;
    }
}

之后使用 $new_result 对象。

ps:在SQL查询中过滤行不是更容易吗?

于 2012-10-26T06:48:52.530 回答