2

我有两个数据表“项目”和“子公司”,结构如下:

项目 ItmCod ItmName

子公司 ItmCod母公司ItmCodChild

我需要显示一个项目列表,每个项目及其子公司列表,就像在这个 json 中一样:

{
   "ItmCod":1,
   "ItmName":"BogusItem1",
   "Subsidiaries":
   [
      {
         "ItmCodParent":1,
         "ItmCodChild":15
      },{
         "ItmCodParent":1,
         "ItmCodChild":16      
      }
   ]
},{
   "ItmCod":2,
   "ItmName":"BogusItem2",
   "Subsidiaries":
   [
      {
         "ItmCodParent":2,
         "ItmCodChild":17
      },{
         "ItmCodParent":2,
         "ItmCodChild":18      
      }
   ]
}

如何将第二个结果集添加到第一个结果集以进行嵌套,如上所示。到目前为止我有这个代码:

$sql = "SELECT ItmCod, ItmName FROM item";

$item_rows = array();

while($item_row = $database->fetch_array_assoc($item_result)){

   $sub_sql = "SELECT ItmCodParent, ItmCodChild FROM subsidiary WHERE subsidiary.ItmCodParent = " . $item_row["ItmCod"];

   $sub_result = $database->query($sub_sql);

   $sub_rows = array();

   while($sub_row = $database->fetch_array_assoc($sub_result)){
      $sub_rows[] = $sub_row;
   }

   $item_rows[] = $item_row;
}

print json_encode($item_rows);

谢谢。

4

3 回答 3

2

就在这条线之上

$item_rows[] = $item_row;

只需添加

$item_row['Subsidiaries']=$sub_rows;
于 2013-04-05T22:13:46.923 回答
1

我会像这样做一个单一的连接查询:

SELECT i.ItmCod AS ItmCod, i.ItmName AS ItmName, s.ItmCodChild AS ItmCodChild
FROM item AS i
INNER JOIN subsidiary AS s
   ON i.ItmCod = s.ItmCodParent

注意我没有选择s.ItmCodParent,因为这只是多余的i.ItmCod.

然后像这样构建数组:

$item_rows = array();
while($item_row = $database->fetch_array_assoc($item_result)){
   $item_rows[(int)$item_row['ItmCod']]['ItmCod'] = $item_row['ItmCod'];
   $item_rows[(int)$item_row['ItmCod']]['ItmName'] = $item_row['ItmCod'];
   $sub_array = array(
       'ItdCodParent' => $item_row['ItmCod'],
       'ItmCodChild' => $item_row['ItmCodChild']
   );
   $item_rows[(int)$item_row['ItmCod']]['Subsidiaries'][] = $sub_array;
}
$item_rows = array_values($item_rows); // reset numerical indexes.
echo json_encode($item_rows);
于 2013-04-05T22:18:46.663 回答
0

我不会尝试通过两个查询来解决这个问题:

$sql = '
    SELECT I.ItmCod, I.ItmName, S.ItmCodChild
    FROM item I
    LEFT JOIN subsidiary S ON (S.ItmCodParent = I.ItmCod)
';

// fetch $item_result with $sql

$item_rows = array();
while ($item_row = $database->fetch_array_assoc($item_result)) {
  $cod = $item_row['ItmCod'];
  if (!array_key_exists($cod, $item_rows)) {
    $item_rows[$cod] = $item_row;
  }

  $item_rows[$cod]['Subsidiaries'] = array(
    'ItmCodParent' => $cod,
    'ItmCodChild' => $item_row['ItmCodChild'],
  );
}

// array_values is because json_encode will keep the keys
// otherwise
print json_encode(array_values($item_rows));

这样一来,您就不必为每个单独的项目行运行额外的查询来获取子公司(最大限度地减少往返时间,并让数据库做它擅长的事情)。

于 2013-04-05T22:23:32.117 回答