Before Explain the code i have to explain structure of data
So I have data in this format
=>Department
==>Category
===>Sub-Category
There are multiple department having multiple categories and those categories have sub-categories.
There can be a many category having same name but different department and same in sub-category and category.
There is table contain all the data and product. I have to extract data in a proper and put in table of
Departments
Categories => fk is Departments id
Subcategories => fk is Categories id
First i am inserting the data in departments
Then In categories first i have get id of department then insert into categories table:
public function insertDataInCategory($data)
{
if(!empty($data)){
//pass data from hierarchy
foreach ($data as $dkey => $drow) {
//get id
$this->db->select('id');
$this->db->from('departments');
$this->db->WHERE('name',$dkey);
$query = $this->db->get();
//getting department it to identify category
$did = $query->result_array();
//adding category from department
foreach ($drow as $ckey => $crow) {
$cat_content = array(
'department_id' => $did[0]['id'] ,
'name' => $ckey ,
'description' => ''
);
$this->db->insert('categories', $cat_content);
}
}
}
}
in subcategories the first i have to get id of department for category and after that i identify that this sub-category belong to that category. So there are 3 queries running here that are increasing the time of execution.
public function insertDataInSubcategory($data)
{
//pass data from hierarchy
if(!empty($data)){
//department foreach
foreach ($data as $dkey => $drow) {
//category each
$this->db->select('id');
$this->db->from('departments');
$this->db->WHERE('name',$dkey);
$query = $this->db->get();
//getting department it to identify category
$did = $query->result();
foreach ($drow as $ckey => $crow) {
//get id
$this->db->select('id');
$this->db->from('categories');
$this->db->WHERE('name',$ckey);
$this->db->WHERE('department_id',$did[0]->id);
$query = $this->db->get();
//getting id of category of sub-category
$cid = $query->result_array();
//sub-category foreach
foreach ($crow as $skey => $srow) {
$scat_content = array(
'category_id' => $cid[0]['id'] ,
'name' => $skey ,
'description' => ''
);
$this->db->insert('sub_categories', $scat_content);
}
}
}
}
}
The functions of insertDataInCategory and insertDataInSubcategory time is increasing drastically. Please tell me how to decrease it time. and proper method to insert into tables
$datathat is passed toinsertDataInCategory($data)and toinsertDataInSubcategory($data)? Please show the structure and a short example of values that might be passed.