我有一个问题,我没有找到解决方案,所以我有2个表:
分类
id category
1 BBA
2 BSCS
3 BEE
Sub_category:
id category_id sub_category_name
1 1 Accountant
2 1 Manager
3 1 Sales
4 2 Data Adminsitrator
5 2 Web Developer
6 3 Airline Pilot
7 3 Airport Security Screener
8 3 Aircraft Mechanic
我想从第一个表加入两个表我想获得类别,在类别下我想要所有sub_category
我的控制器看起来像这样:
public function getVehicles()
{
$result = $this->crud_m->getUserVehicles($data,'vehicle');
return $this->output->set_output(json_encode(array(
'status' => 'OK',
'statusCode' => '402',
'response' => array(
'description' => 'Details',
'category'=> $result
)
)));
}
我的模型是这样的:
public function getUserVehicles($data)
{
$this->db->select('*');
$this->db->from('categories');
$this->db->join('sub_category','sub_category.category_id=categories.id');
$this->db->group_by('categories.id');
$query = $this->db->get();
$result = $query->result();
if(empty($result)){
return '401';
}
else{
return $result;
}
}
我的输出现在是这样的:
{
"status": "OK",
"statusCode": "402",
"response": {
"description": "Details",
"category": [
{
"id": "1",
"category": "BBA",
"category_id": "1",
"sub_category_name": "Accountant"
},
{
"id": "4",
"category": "BSCS",
"category_id": "2",
"sub_category_name": "Data Adminsitrator"
},
{
"id": "6",
"category": "BEE",
"category_id": "3",
"sub_category_name": "Airline Pilot"
}
]
}
}
我需要的是这样的:
[
{
"categoryId": "1",
"category": "BBA",
"subCategory": [
{
"subCategoryId": "1",
"subCategoryName": "Accountant"
},
{
"subCategoryId": "2",
"subCategoryName": "Manager"
},
{
"subCategoryId": "3",
"subCategoryName": "Sales"
}
]
},
{
"categoryId": "2",
"category": "BSCS",
"subCategory": [
{
"subCategoryId": "4",
"subCategoryName": "Data Adminsitrator"
},
{
"subCategoryId": "5",
"subCategoryName": "Web developer"
}
]
}
]
答案 0 :(得分:0)
您可以使用以下代码来获取数据。
public function getUserVehicles($data)
{
$categories = array();
$this->db->select('*');
$this->db->from('categories');
$query = $this->db->get();
$result = $query->result();
foreach($result as $r){
$r['subCategory'] = $this->getSubCategory($r['id']);
array_push($categories, $r);
}
if(empty($result)){
return '401';
}else{
return $categories;
}
}
public function getSubCategory($cat)
{
$this->db->select('*');
$this->db->from('sub_category');
$this->db->where('id', $cat);
$query = $this->db->get();
$result = $query->result();
return $result;
}