I have 2 tables in MySql
Section
section_id name
=====================
1 Section1
2 Section2
Category
category_id section_id name
=========================================
1 1 Category1
2 1 Category2
3 2 Category3
4 2 Category3
This is what I have now:
$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);
The result has came out is like this:
{sectionlist:[
{sectionName: "Section1", categoryList: [{categoryName: "category1"}]},
{sectionName: "Section1", categoryList: [{categoryName: "category2"}]},
{sectionName: "Section2", categoryList: [{categoryName: "category3"}]},
{sectionName: "Section2", categoryList: [{categoryName: "category4"}]},
]}
This wasn't the expected result from me, I would like to have an object that look like this:
{sectionlist:[
{sectionName: "Section1", categoryList: [{categoryName: "category1"}, {categoryName: "category2"}]},
{sectionName: "Section2", categoryList: [{categoryName: "category3"}, {categoryName: "category4"}]}
]}
Therefore, how can I group the section 1 with section 1 and section with section 2?