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条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)