【发布时间】:2018-08-15 13:21:47
【问题描述】:
我的数据库中有一个表,其结构和数据如下:
---------------------------------------------
id | type | name | age
---------------------------------------------
1 F-A jon 24
2 F-A roy 25
3 F-E robert 26
4 F-E sina 25
我想根据type的值对数据进行分组,生成一个专门的结构化数组,生成如下json:
{
type:{
"F-A": [
{
"name": "jon",
"age": "24"
"id": "1"
},
{
"name": "roy",
"age": "25",
"id": "2"
}
],
"F-E": [
{
"name": "robert",
"age": "26",
"id": "3"
},
{
"name": "sina",
"age": "25",
"id": "4"
},
]
}
}
请注意,每个唯一类型子数组都包含与值关联的行数据集合。
我的模特:
public function prescriptionData(){
$table = 'prescription';
$this->db->select('*');
$this->db->from($table);
$query=$this->db->get();
$locations = [];
//===
$val4=[];
$this->db->select('type,name,age,id');
$this->db->from($table);
$query2=$this->db->get();
Foreach($query2->result() as $k=>$va13){
$val4[$k]= $va13;
}
foreach($query2->result_array() as $val){
if(isset($val['type'])){
$locations[type][$val['type']]=$val4;
}else{
$locations[type][$val['type']]= $val4;
}
}
return $locations;
}
我的控制器:
public function prescription(){
$userCount['result'] = $userCount1 = $this->Querydata->prescriptionData();
if($userCount['result']>0){
$validation = array(
"responseCode" => $this->res = 200,
"responseMessage" => $this->login = 'Training programs details successfully added',
"data" => $this->data = $userCount['result'] );
echo json_encode($validation);
这是我不正确的 json 响应:
"type": {
"F-A": [
{
"type": "F-A",
"name": "Jon",
"age": "24",
"id": "1"
},
{
"type": " F-A",
"name": "roy",
"age": "25",
"id": "2"
},
{
"type": "F-E",
"name": "robert",
"age": "26",
"id": "3"
},
{
"type": " F-E",
"name": "sina",
"age": "25",
"id": "4"
}
],
" F-A": [
{
"type": "F-A",
"name": "Jon",
"age": "24",
"id": "1"
},
// etc.
【问题讨论】: