You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OOP认知框架中用implode处理多选表单的ust_id值?

问题

现有一段原生PHP代码,可将POST提交的多选ust_id数组转换为逗号分隔的字符串:

$arrayUstKat = array();
if(isset($_POST["ust_id"]))
{
foreach ($_POST["ust_id"] as $UstKat)
$arrayUstKat[] =$UstKat;
}  
$stringSTR = implode(",", $arrayUstKat);

需要将该逻辑整合到以下OOP框架代码中,但当前框架的post方法仅能获取单个表单值,无法处理多选数组,需实现将多选ust_id值拼接后传入模型的add方法:

$insert = $this->urun_kategori_model->add(
array(
"title"         => $this->input->post("title"),
"ust_id"        => $this->input->post("ust_id"),
"isActive"      => 1,
"createdAt"     => date("Y-m-d H:i:s")
)
);

public function post($index = NULL, $xss_clean = NULL)
{
return $this->_fetch_from_array($_POST, $index, $xss_clean);
}

解决方案

方式一:直接在调用处处理数组

无需修改框架核心方法,直接在构造add方法的参数时手动处理ust_id数组:

// 直接从$_POST获取数组,绕过框架post方法的限制
$ustIds = isset($_POST['ust_id']) ? $_POST['ust_id'] : [];
// 拼接为逗号分隔字符串,array_filter可过滤空值(可选)
$ustIdStr = implode(',', array_filter($ustIds));

$insert = $this->urun_kategori_model->add(
    [
        "title"         => $this->input->post("title"),
        "ust_id"        => $ustIdStr,
        "isActive"      => 1,
        "createdAt"     => date("Y-m-d H:i:s")
    ]
);

如果需要保留框架的XSS过滤机制,可以直接调用底层的_fetch_from_array方法获取数组:

$ustIds = $this->input->_fetch_from_array($_POST, 'ust_id', TRUE); // 第三个参数开启XSS清理
$ustIdStr = !empty($ustIds) ? implode(',', $ustIds) : '';

方式二:扩展框架的post方法支持数组拼接

修改框架的post方法,增加一个参数控制是否将数组拼接为字符串:

public function post($index = NULL, $xss_clean = NULL, $implodeArray = FALSE)
{
    $value = $this->_fetch_from_array($_POST, $index, $xss_clean);
    
    // 若目标值是数组且需要拼接,返回逗号分隔字符串
    if ($implodeArray && is_array($value)) {
        return implode(',', array_filter($value));
    }
    
    return $value;
}

之后调用时只需传入第三个参数TRUE即可自动处理:

$insert = $this->urun_kategori_model->add(
    [
        "title"         => $this->input->post("title"),
        "ust_id"        => $this->input->post("ust_id", NULL, TRUE),
        "isActive"      => 1,
        "createdAt"     => date("Y-m-d H:i:s")
    ]
);

内容的提问来源于stack exchange,提问作者Cemil Ulusoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 01:52:46