Reputation: 2388
I am getting the Nameno from the database like below format.
$form_data['Nameno']='1,2,3,4';
$getName=$this->Home_model->getNameData($form_data['Nameno']);
Now I am passing that Nameno to the model to get the Name. So I used explode
and passing to the foreach
Model
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;
}
I need an output from my model like $getName='ABC,XYZ,POD,RED'
After suggested @Barmar answer
controller
$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);
Model
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;
}
Would you help me out in this issue?
Upvotes: 0
Views: 53
Reputation: 782105
You need to explode the original data into an array, call the function on each element, then implode the result back into a string.
$ids = explode(',', $form_data['Nameno']);
$names = array();
foreach ($ids as $id) {
$nameData = $this->Home_model->getNameData($id);
$names[] = $nameData[0]->templateName;
}
$getNames = implode(',', $names);
Upvotes: 1
Reputation: 41820
Instead of running multiple queries in a loop, you can use where_in()
to get the results with one query.
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);
}
Upvotes: 1