2

我在 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 部分分组?

4

2 回答 2

2

要回答您的问题,您首先要创建类别数组。

for ($i=0; $i < mysql_num_rows($sections); $i++ ){
    $categorylist = array();
    for ($j=0; $j < mysql_num_rows($categories); $j++){
        if (mysql_result($sections,$i,"section_id") == mysql_result($categories,$j,"section_id")){
            $categorylist[] = array('category' => mysql_result($categories,$j,"name");
        }
    }
    $result['sectionlist'][] = array('sectionName' => mysql_result($sections,$i,"name"), 'categorylist' => $categorylist));
}

作为旁注,PHP 鼓励使用其他数据库扩展

于 2012-08-17T00:26:50.243 回答
1

@Greg 的评论非常重要,需要注意上面的内容。另外,我建议将您的查询重写为带有连接的单个查询,以便仅检索您想要的数据。我不是 100% 确定你需要什么,但它可能是这样的:

SELECT section.section_id, category.name, section.name FROM category 
  LEFT JOIN section ON section.section_id = category.section_id;

这将返回一个类别名称数组,这些名称与它们关联的 section_id 和部分名称键控(如果您愿意,您也可以选择 category_id)。

于 2012-08-17T00:29:30.300 回答