我在 MySql 中有 2 个表
部分
section_id name
=====================
1 Section1
2 Section2
类别
category_id section_id name
=========================================
1 1 Category1
2 1 Category2
3 2 Category3
4 2 Category3
这就是我现在所拥有的:
$sections = mysql_query($sql_section) or die("Could not execute query.");
$categories = mysql_query($sql_category) or die("Count not execute query");
$result = array('sectionlist' => array());
for ($i=0; $i < mysql_num_rows($sections); $i++ ){
for ($j=0; $j < mysql_num_rows($categories); $j++){
if (mysql_result($sections,$i,"section_id") == mysql_result($categories,$j,"section_id")){
$result['sectionlist'][] = array('sectionName' => mysql_result($sections,$i,"name"), 'categorylist' => array(array('category' => mysql_result($categories,$j,"name"))));
}
}
}
echo json_encode($result);
结果出来是这样的:
{sectionlist:[
{sectionName: "Section1", categoryList: [{categoryName: "category1"}]},
{sectionName: "Section1", categoryList: [{categoryName: "category2"}]},
{sectionName: "Section2", categoryList: [{categoryName: "category3"}]},
{sectionName: "Section2", categoryList: [{categoryName: "category4"}]},
]}
这不是我的预期结果,我想要一个看起来像这样的对象:
{sectionlist:[
{sectionName: "Section1", categoryList: [{categoryName: "category1"}, {categoryName: "category2"}]},
{sectionName: "Section2", categoryList: [{categoryName: "category3"}, {categoryName: "category4"}]}
]}
因此,如何将第 1 部分与第 1 部分和第 2 部分分组?