php - 从数据库结果 PHP 构建 JSON
问题描述
我有一个表格行如下,
在此处输入图像描述DB 返回行如下所示
从上面的结果,我必须像下面那样构建 JSON,
如果用户从用户界面选择按“TARGETDATE”之类的列进行分组,然后是“ASSIGNEE”,然后是“SUBCATEGORY”,那么我想准备如下的json
[
{
"key": "21-AUG-20",
"items": [
{
"key": "VINAY",
"items": [
{
"key": "FEATURE",
"items": null,
"count": 1,
"summary": []
}],
"count": 1,
"summary": []
}],
"count": 1,
"summary": []
},
{
"key": "22-AUG-20",
"items": [
{
"key": "ASHWIN",
"items": [
{
"key": "Bug",
"items": null,
"count": 1,
"summary": []
}],
"count": 1,
"summary": []
},
{
"key": "DIVYA",
"items": [
{
"key": "TEST",
"items": null,
"count": 1,
"summary": []
}],
"count": 1,
"summary": []
}
],
"count": 2,
"summary": []
},
{
"key": "25-AUG-20",
"items": [
{
"key": "VINAY",
"items": [
{
"key": "LIVE",
"items": null,
"count": 1,
"summary": []
}],
"count": 1,
"summary": []
}],
"count": 1,
"summary": []
}
]
如果用户从用户界面选择按“TARGETDATE”等列分组,然后是“ASSIGNEE”,那么我想构建如下的json
[
{
"key": "21-AUG-20",
"items": [
{
"key": "VINAY",
"items": [],
"count": 1,
"summary": []
}],
"count": 1,
"summary": []
},
{
"key": "22-AUG-20",
"items": [
{
"key": "ASHWIN",
"items": [],
"count": 1,
"summary": []
},
{
"key": "DIVYA",
"items": [],
"count": 1,
"summary": []
}
],
"count": 2,
"summary": []
},
{
"key": "25-AUG-20",
"items": [
{
"key": "VINAY",
"items": [],
"count": 1,
"summary": []
}],
"count": 1,
"summary": []
}
]
在这里,用户可以灵活地按 1 到 N 列分组,我尝试了按单列分组的代码,这是非常简单的任务,
我试过的代码
if(isset($rowsArr[$tRow["TARGETDATE"]])){
$rowsArr[$tRow["TARGETDATE"]] = $rowsArr[$tRow["TARGETDATE"]] + 1;
}else{
$rowsArr[$tRow["TARGETDATE"]] = 1;
}
$filteredResult = array();
foreach($rowsArr as $key => $val){
$temp = array();
$temp["key"] = $key;
$temp["items"] = null;
$temp["count"] = $val;
$temp["summary"] = null;
array_push($filteredResult,$temp);
}
仅在为一列(TARGETDATE)完成分组时才这样做。按多列分组时如何构建json结构?