2 回答

TA貢獻(xiàn)1845條經(jīng)驗 獲得超8個贊
要刪除進(jìn)入數(shù)據(jù)庫的無關(guān)逗號,您可以根據(jù)自己的喜好使用array_filter, trim, 或。preg_replace
$this->input->post('coresubjs[]')理論值為
array(
? ?'',
? ?'',
? ?'0',
? ?'A',
? ?'B',
? ?'',
? ?'D',
? ?'',
? ?'',
);
僅使用implode(',')
會導(dǎo)致
,,0,A,B,,D,,
免責(zé)聲明
但是請記住,post 值中的任何逗號都不會被正確解釋,應(yīng)該使用其他方式進(jìn)行轉(zhuǎn)義。例如:1,000
將被分解為array("1", "000")
.?出于這個原因,我建議重構(gòu)以支持使用json_encode()
andjson_decode()
或serialize()
and?unserialize()
,而不是implode(',')
andexplode(',')
數(shù)組過濾器
從數(shù)組參數(shù)中刪除“空”值 (?0, "", false, null
)?implode
。這將適用于任何空的輸入值,包括數(shù)組的中間值。
implode(',',?array_filter($this->input->post('coresubjs[]')))
結(jié)果
請注意,所有無關(guān)的逗號和0
值都已刪除
A,B,D
要避免諸如 之類的“空”值的問題0, false
,您可以改用自定義回調(diào)。
implode(',',?array_filter($this->input->post('coresubjs[]'),?function($value)?{????return?null?!==?$value?&&?''?!==?$value; }))
結(jié)果
通知所有無關(guān)的逗號都被刪除
0,A,B,D
修剪
僅從值中刪除前導(dǎo)和尾隨逗號implode
。
trim(implode(',',?$this->input->post('coresubjs[]')),?',')
結(jié)果
請注意,前導(dǎo)逗號和尾隨逗號已被刪除,但中間的額外逗號保留了下來。
0,A,B,,D
preg_replace
類似于trim
,從值中刪除前導(dǎo)和尾隨逗號implode
,并用單個逗號替換中間的任何 2 個或更多逗號。
preg_replace(['/,{2,}/',?'/^,+/',?'/,+$/'],?[',',?'',?''],?implode(',',?$this->input->post('coresubjs[]')))
圖案說明:
,{2,}
任何 2 個或更多逗號^,+
以1個或多個逗號開頭,+$
以 1 個或多個逗號結(jié)尾
結(jié)果
通知所有無關(guān)的逗號已被刪除
0,A,B,D

TA貢獻(xiàn)1846條經(jīng)驗 獲得超7個贊
在你的update_core function,你需要trim額外的','。你可以這樣做 -
public function update_core(){
$data = array(
'core_subjects' => rtrim(implode(',', $this->input->post('coresubjs[]')), ','); // remove the extra ',' to the right
);
$this->db->where('id', $this->input->post('coresubjID'));
return $this->db->update('subjects', $data);
}
另外,請記住,您不必在每次更新時都刪除數(shù)據(jù)。更新時它會自動覆蓋以前的值。所以你的remove_core方法是多余的,應(yīng)該刪除
- 2 回答
- 0 關(guān)注
- 131 瀏覽
添加回答
舉報