有没有一种快速的方法可以不使用复杂的for循环系列(使用像Underscore这样的东西?或者改进我的MySQL查询?)来获取格式化为这样的平面列表的数据:
[
{
"J_NUM": "BOAK-1212",
"X_DUE_DATE": "2012-06-20T00:00:00.000Z",
"X_LEAD_TIME": 0,
"X_NAME": "Mail List Due",
},
{
"J_NUM": "BOAK-1212",
"X_DUE_DATE": "2012-06-08T00:00:00.000Z",
"X_LEAD_TIME": 0,
"X_NAME": "Vendor Specs 2",
},
{
"J_NUM": "JEFF-2000",
"X_DUE_DATE": "2012-06-11T00:00:00.000Z",
"X_LEAD_TIME": 0,
"X_NAME": "Client Final Approval",
},
{
"J_NUM": "JEFF-2000",
"X_DUE_DATE": "2012-06-08T00:00:00.000Z",
"X_LEAD_TIME": 0,
"X_NAME": "Vendor Specs 2",
}
]
并根据某些参数对其进行嵌套/分组,在本例中为J_NUM
,以便它如下所示:
[
{
"J_NUM": "BOAK-1212",
"SCHEDULE_SERIES": [
{
"X_DUE_DATE": "2012-06-20T00:00:00.000Z",
"X_LEAD_TIME": 0,
"X_NAME": "Mail List Due",
},
{
"X_DUE_DATE": "2012-06-08T00:00:00.000Z",
"X_LEAD_TIME": 0,
"X_NAME": "Vendor Specs 2",
}
]
},
{
"J_NUM": "JEFF-2000",
"SCHEDULE_SERIES": [
{
"X_DUE_DATE": "2012-06-11T00:00:00.000Z",
"X_LEAD_TIME": 0,
"X_NAME": "Client Final Approval",
},
{
"X_DUE_DATE": "2012-06-08T00:00:00.000Z",
"X_LEAD_TIME": 0,
"X_NAME": "Vendor Specs 2",
}
]
}
]
答案 0 :(得分:2)
在while循环中,您可以构建所需的输出:
$query = "SELECT ...";
$result = mysqli_query($link, $query);
$out = array();
while($row=mysqli_fetch_assoc($result)) {
$J_NUM = $row['J_NUM'];
if(!array_key_exists($J_NUM, $out)) {
$out[$J_NUM] = array("J_NUM" => $J_NUM, "SCHEDULE_SERIES" => array());
}
$out[$J_NUM]['SCHEDULE_SERIES'][] = array(
"X_DUE_DATE" => $row['X_DUE_DATE'],
"X_LEAD_TIME" => $row['X_LEAD_TIME'],
"X_NAME" => $row['X_NAME']);
}
$out = json_encode(array_values($out), true);
答案 1 :(得分:0)
使用Underscore计算出来。
_.groupBy(theData, 'J_NUM')
将返回以下内容:
{"BOAK-1212":[
{"J_NUM":"BOAK-1212",
"X_DUE_DATE":"2012-06-20T00:00:00.000Z",
"X_LEAD_TIME":0,
"X_NAME":"Mail List Due"},
{"J_NUM":"BOAK-1212",
"X_DUE_DATE":"2012-06-08T00:00:00.000Z",
"X_LEAD_TIME":0,
"X_NAME":"Vendor Specs 2"}
],
"JEFF-2000":[
{"J_NUM":"JEFF-2000",
"X_DUE_DATE":"2012-06-11T00:00:00.000Z",
"X_LEAD_TIME":0,
"X_NAME":"Client Final Approval"},
{"J_NUM":"JEFF-2000",
"X_DUE_DATE":"2012-06-08T00:00:00.000Z",
"X_LEAD_TIME":0,
"X_NAME":"Vendor Specs 2"}
]}