PHP codeIgniter:从标识

时间:2016-12-23 09:49:35

标签: php mysql algorithm codeigniter foreach

我想从二维表中删除一个问题。

我将举一个更明确的例子(使用我所关心的函数)。

我的功能目前给了我以下错误的结果我想删除问题32(id = 32),所以我的数据库列中有这些行 qids

初始状态

**qids**  

+++++++++

10,13,56

+++++++++

1,95,2,45,12

+++++++++

1,32,54,10

在治疗结束时,我的DB线看起来像这样:

错误的实际结果

**qids**  

+++++++++

1,54,10

+++++++++

1,54,10

+++++++++

1,54,10

但我希望在我的数据库表中有这个:

我想要什么

**qids**  

+++++++++

10,13,56

+++++++++

1,95,2,45,12

+++++++++

1,54,10

我的功能:

function remove_question($qid) {

    $this->db->select("qids");         //column name
    $query = $this->db->get('savsoft_quiz'); //table name
    $quiz = $query->result_array();

    foreach($quiz as $value) {

        $new_qid = array();

        foreach(explode(',', $value['qids']) as $key => $oqid) {

            if ($oqid != $qid) {

                $new_qid[] = $oqid;
                $userdata = array(
                    'qids' => implode(',', $new_qid)
                );

                $this->db->update('savsoft_quiz', $userdata);
            }
        }
    }

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

基本上你错过了where声明。它使您调用更新整个表。此外,update调用需要退出第二个foreach

function remove_question($qid) {

    $quiz = $this->db->select("qids")
                    ->get('savsoft_quiz')
                    ->result_array();

    // Foreach row
    foreach($quiz as $value) {

        $found = FALSE;         
        $new_qid = array();

        // For each id in the comma separated 
        foreach(explode(',', $value['qids']) as $key => $oqid) {

            // Adds still wanted ids to new array
            if ($oqid != $qid) {    
                $new_qid[] = $oqid;                
            } else {
                $found = TRUE;
            }   
        }

        // If the number was found in that row, updates DB
        if($found){
            // Implodes values
            $userdata = array(
                'qids' => implode(',', $new_qid)
            );

            $this->db->where('qids', $value['qids'])
                    ->update('savsoft_quiz', $userdata);
        }
    }
}

答案 1 :(得分:0)

试试这样......

function remove_question($qid) {

    $this -> db -> select("qids");         //column name
    $query = $this ->db-> get('savsoft_quiz'); //table name
    $q= $query -> row();
    $quiz=$q->qids;

    $new_qid = array();
    $data=explode(',', $quiz);
    foreach ($data as $d) {
            if ($d != $qid) {
                array_push($new_qid,$d);//push the id if not equal
            }
    }
    $new_row=implode(',',$new_qid);
    //try using echo $new_row;
    return $new_row; //ids after removing
    }

请参阅以下示例...了解更多

 $quiz ="1,54,11,1,54,10,32,1,11,10";

    $new_qid = array();
    $data=explode(',',$quiz);
    // print_r($data);die();
    foreach($data as $d) {
            if ($d != 32) {
                array_push($new_qid,$d);//push the id if not equal
            }
    }
    $new_row=implode(',',$new_qid);
    echo $new_row;