簡體   English   中英

如何將foreach數據從模型發送到控制器

[英]How to send the foreach data from the model to the controller

我從數據庫獲取Nameno,如下所示。

$form_data['Nameno']='1,2,3,4';

$getName=$this->Home_model->getNameData($form_data['Nameno']);

現在,我將該Nameno傳遞給模型以獲取Name。 所以我使用了explode並傳遞到foreach

模型

public function getNameData($NameId){

     $getTempid=explode(",",$NameId);

    $arrayData=[];
    foreach ($getTempid as $row){
    $where = array('is_tempActive' => 1,'Name_id'=>$row);

    $this->db->select('templateName');
    $this->db->from('tbl_templatename');
    $this->db->where($where);
    $query = $this->db->get();
    $result = $query->result();

    //print_r($result);
    //$arrayData[]=$result;

    }
    return $result;
}

我需要模型的輸出,例如$getName='ABC,XYZ,POD,RED'

建議@Barmar回答后

控制者

$ids = explode(',', $form_data['Nameno']);
$names = array();
foreach ($ids as $id) {
    $names[] = $this->Home_model->getNameData($id)->templateName;;
   // print_r($names);
}

$getNames = implode(',', $names);
print_r($getNames);

模型

public function getNameData($tempId){

    $where = array('is_tempActive' => 1,'Name_id'=>$row);

    $this->db->select('templateName');
    $this->db->from('tbl_templatename');
    $this->db->where($where);
    $query = $this->db->get();
    $result = $query->result();
    return $result;
}

您能幫我解決這個問題嗎?

您需要將原始數據分解為數組,在每個元素上調用函數,然后將結果內插到字符串中。

$ids = explode(',', $form_data['Nameno']);
$names = array();
foreach ($ids as $id) {
    $nameData = $this->Home_model->getNameData($id);
    $names[] = $nameData[0]->templateName;
}
$getNames = implode(',', $names);

您可以使用where_in()來獲得一個查詢的結果,而不是循環運行多個查詢。

public function getNameData($NameId){

    $getTempid = explode(",", $NameId);

    $this->db->select('Name');
    $this->db->from('tbl_templatename');
    $this->db->where('is_tempActive', 1);
    $this->db->where_in($getTempid);

    $query = $this->db->get();
    $result = $query->result();

    foreach ($query->result() as $row) {
         $names[] = $row->Name;
    }
    return implode(',', $names);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM