Search code examples
phpmysqljsonencode

How to design an Array Structure and Encode to Json using PHP?


I have 2 tables in MySql

Section

ID       Name
=====================
1        Section1
2        Section2

Category

ID        SectionID     Name
=========================================
1           1           Category1
2           1           Category2
3           2           Category3

This is what I have now:

$sql_section = "select * from section";<br>
$sql_category = "select * from category";<br>
$result_section = mysql_query($sql_section) or die("Could not execute query.");
$result_category = mysql_query($sql_category) or die("Could not execute query.");

echo json_encode(???????);

And I would like to Encode JSON in PHP to get the result that looks like this:

{sections:[
{sectionName: "Section1", categoryList: [{categoryName: "category1"},
              {categoryName: "category2"}]},
{sectionName: "Section1", categoryList: [{categoryName: "category3"}]}<br>
]}

Any clue of how can I design an array that looks like this?


Solution

  • $arr = array('sections' => array());
    $arr['sections'][] = array('sectionName' => array('categoryList' => array( array('categoryName' => 'Category 1'), array('categoryName' => 'Category 2'))));
    $arr['sections'][] = array('sectionName' => array('categoryList' => array( array('categoryName' => 'Category 3'), array('categoryName' => 'Category 4'))));
    echo json_encode($arr);
    

    output://

    {"sections":[
       {"sectionName":
          {"categoryList":
             [{"categoryName":"Category 1"},
              {"categoryName":"Category 2"}]}
          },
        {"sectionName":
          {"categoryList":
             [{"categoryName":"Category 3"},{"categoryName":"Category 4"}]}}]}
    

    You'll just need to replace the string values with variables and put it in the loop to create the required data set.