douyong4842 2010-09-07 09:42
浏览 57
已采纳

使用PHP和MYSQL构建多维关联数组

I'm trying to build a multidimensional associative array while fetching the results from a MySQL query. But i can't figure out how to achieve this. I want to build an array like this one:

 array ("cat_name" => "category1",
 "id_cat" => "1",
 "sub_cat" => array ("name_sub_cat" => "subCategory",
"id_sub_cat" => "4",
       "ss_cat" =>array ("ss_cat_name" =>"ss_cat1",
    "id_ss_cat" => "4"
                           )
       )
  );

Here's where i'm building the array:
Edit : I've ended up with something like that, not very sexy, but if think i'm almost there

while($row = mysql_fetch_assoc($resultQueryCat)){
    $menuArray[$row["id_cat"]]["cat_name"] = $row["cat_name"];
    $menuArray[$row["id_cat"]][$row["id_sub_cat"]]["id_sub_cat"] = $row["id_sub_cat"];
    $menuArray[$row["id_cat"]][$row["id_sub_cat"]]["name_sub_cat"] = $row["name_sub_cat"];
    $menuArray[$row["id_cat"]][$row["id_sub_cat"]][$row["ss_cat_name"]]["ss_cat_name"] =     $row["ss_cat_name"];
    $menuArray[$row["id_cat"]][$row["id_sub_cat"]][$row["ss_cat_name"]]["id_ss_cat"] = $row["id_ss_cat"];
                                     }

Edit2: The code to display the array

    $menu.='<ul>';
    foreach ($menuArray as $key) { 
       $compteur_cat++;
       $menu.= '<div id="collapsiblePanelCol'.$compteur_cat.'"    class="collapsiblePanelCol floatleft">
        <li class="categorie"> '.$key["cat_name"].'
           <ul>';
  foreach ($key as $key1) {
if (is_array($key1){/* One of the thing i forgot which totally screwed up my results*/
    $menu.= '<ul>
       <li class="ss_categorie">'.$key1["name_sub_cat"].'<ul>';
    foreach ($key1 as $key2) {
              if (is_array($key2)){ 
                   $menu.= '<li class="element">'.$key2["ss_cat_name"].'</li>'; }
                              }  
    $menu.= '</ul></li></ul>';
                   }
                }
$menu.='</ul>
   </li>
  </div>';
  } 
  $menu.= '</ul>';

Thanks.

Final Edit: My code is working :) i edited the previous code to make it correct

  • 写回答

2条回答 默认 最新

  • dongxie2613 2010-09-07 09:46
    关注

    It's not an easy task, as data from DB might contain loops :-)

    I'd better save it in id->data hashmap so that you can build the structure easier.

    Not sure why you need multidimensions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加