For each loop not working
I've some master categories and user groups, user groups are assigned to master categories. I am using the following code but it only display the last record in the table while I need to display all matching records.
Function in controller:
function listdesignation($id) {
$res = $this->designation_model->GetDesignation($id);
$this->data['test'] = $res;
if ($res) {
foreach ($res as $row) {
$this->data['selected_designation'] = $this->designation_model->GetDesignation_Names($row['designation_id']);
}
if ($this->data['selected_designation']) {
$this->data['enable_view'] = true;
}
}
}
Function in model:
function GetDesignation_Names($id) {
$designation = array();
$this->db->select('*');
$this->db->from('delta_designation');
$this->db->where('designation_id', $id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$designation[$row->designation_id]['designation_id'] = $row->designation_id;
$designation[$row->designation_id]['designati开发者_StackOverflow中文版on'] = $row->designation;
}
return $designation;
}
return false;
}
You're overwriting your variable with each iteration through your foreach
loop. You probably want to build up an array instead.
E.g. instead of
foreach (...) {
$myvar = $row->field;
}
Try this:
$myresult = array();
foreach (...) {
$myvar = $row->field;
$myresult[]= $myvar; // (append to array)
}
Then you can:
foreach ($myresult as $onerow) {
...
}
精彩评论