根据codeigniter中的外键从两个表中获取json编码数据
Posted
技术标签:
【中文标题】根据codeigniter中的外键从两个表中获取json编码数据【英文标题】:Get json encode data from two tables on the basis of foreign key in codeigniter 【发布时间】:2018-03-25 15:22:25 【问题描述】:我有一个问题要问你,我还没有找到解决方案,所以我有 2 个表:
分类:
id category
1 BBA
2 BSCS
3 BEE
子类别:
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
我想从第一个表中加入两个表,我想获取类别,在类别下我想要所有子类别
我的控制器如下所示:
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"
]
]
【问题讨论】:
您需要从类别记录集中获得一个 for 循环,并将其附加到返回数组中。 删除$this->db->group_by('categories.id');
然后你将拥有所有行。循环结果并根据您的要求创建单独的数组
【参考方案1】:
您可以使用以下代码随意获取数据。
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;
【讨论】:
以上是关于根据codeigniter中的外键从两个表中获取json编码数据的主要内容,如果未能解决你的问题,请参考以下文章
PHP Laravel 根据投票表的外键从问题表中获取所有问题