Json Menu Structure from MySQL

后端 未结 1 1352
深忆病人
深忆病人 2021-01-28 16:00

I have been going round and round with this issue, seemed very simple. I am trying to produce a menu/submenu json out put with PHP/MYSQL: These are the tables:

          


        
1条回答
  •  闹比i
    闹比i (楼主)
    2021-01-28 16:34

    • First off I assume your data goes like this -

    INSERT INTO menu
    (id, parentmenu, name)
    VALUES
    (1,1,"history"),
    (2,1,"owners"),
    (3,1,"news"),
    (4,2,"address"),
    (5,2,"map"),
    (6,3,"jeans"),
    (7,3,"tables"),
    (8,3,"shoes");


    INSERT INTO menuHome
    (id,titleName)
    VALUES
    (1,"About Us"),
    (2,"Contact Us"),
    (3,"Products");

    • secondly i will suggest you to change your query to -

    SELECT pm.id, cm.id, pm.titleName, cm.name FROM menu as cm
    LEFT JOIN (menuHome as pm)
    ON (pm.id = cm.parentmenu);


    • third, lets get to coding


    for our purposes we want something like this -

    $arys = ["menu"=>["sections" => [
    ["title" => "About Us", "items" => [
    ["name"=>"History","id"=>1],
    ["name"=>"Owners","id"=>2],
    ["name"=>"News","id"=>3]
    ]],
    ["title" => "Contact Us", "items" => [
    ["name"=>"Address","id"=>4],
    ["name"=>"Map","id"=>5]
    ]],
    ["title" => "Products", "items" => [
    ["name"=>"Jeans","id"=>6],
    ["name"=>"Tables","id"=>7],
    ["name"=>"Shoes","id"=>8]
    ]]
    ]
    ]
    ];

    So let's build it up

    $querys = "Select pm.id AS pmd , cm.id AS cmd, pm.titleName AS pmt, cm.name AS cmt from menu as cm left join (menuHome as pm) on (pm.id = cm.parentmenu) Order By pmd, cmd ";
    $result = mysql_query($querys);
    $jsary = ["menu" => ["sections" => []]];
    $lastPid = 0;
    $currentPid = 0;
    $title = "";
    $ifff = 0;
    $elss = 0;
    while($row = mysql_fetch_array($result))
    {
            $currentPid = $row['pmd'];
            $title = $row['pmt'];

        $cmd = $row['cmd'];
        $cmt = $row['cmt'];
    
        if($lastPid != $currentPid)
        {
                $insAry = [];
                $insAry = ["title"=> $title, "items" => [["name" => $cmt, "id" => $cmd]]];
                array_push($jsary["menu"]["sections"], $insAry);
                $lastPid = $currentPid;
                $ifff = $ifff + 1;
                $currentPid = 0;
        }
        else
        {
                $ind = 0;
                if($ifff > 0)
                {
                        $ind = $ifff-1;
                }
                $insAry = [];
                $insAry = ["name" => $cmt, "id" => $cmd];
                array_push($jsary["menu"]["sections"][$ind]["items"], $insAry);
        }}
    

    Now just call json_encode()

    json_encode($jsary);

    You'll have your desired output

    0 讨论(0)
提交回复
热议问题