0

有没有一种快速的方法,而不使用一系列复杂的 for 循环(使用诸如下划线之类的东西?或者改进我的 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",
      }
    ]
  }
]
4

2 回答 2

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);
于 2013-10-11T22:24:41.737 回答
0

使用下划线弄清楚了。

_.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"}
]}
于 2013-10-14T02:10:20.297 回答