2017-07-26 72 views
0

我有關於多維數組的問題。Array Formating

我想通過mysql和php創建嵌套菜單。

當我從這個

$ref = []; 
$items = []; 
foreach($row as $row) { 
    $thisRef =& $ref[$row->id]; 
    $thisRef['parent_id'] = $row->parent_id; 
    $thisRef['menu_id'] = $row->menu_id; 
    $thisRef['type'] = $row->type; 
    $thisRef['id'] = $row->id; 
    if($row->parent_id == 0) { 
     $items[] =& $thisRef; 
    } else { 
     $ref[$row->parent_id]['sub'][] =& $thisRef; 
    } 
} 

它生成這樣的陣列創建多維數組。

Array(
    [0] => Array 
     (
      [parent_id] => 0 
      [menu_id] => 10 
      [type] => p 
      [id] => 93 
     ) 
    [1] => Array 
     (
      [sub] => Array 
       (
        [0] => Array 
         (
          [parent_id] => 88 
          [menu_id] => 10 
          [type] => b 
          [id] => 92 
          [sub] => Array 
           (
            [0] => Array 
             (
              parent_id] => 92 
              [menu_id] => 8 
              [type] => c 
              [id] => 94 
             ) 
           ) 
         ) 
        [1] => Array 
         (
          [parent_id] => 88 
          [menu_id] => 8 
          [type] => c 
          [id] => 90 
         ) 

       ) 

      [parent_id] => 0 
      [menu_id] => 5 
      [type] => p 
      [id] => 88 
     ) 
    ) 
) 

其不錯,但我想改變第二陣列鍵子的名字我的意思是,如果陣列中的所有準備好有次,第二次將subofsub,我希望我解釋得很好,我試圖檢查與isset和array_key_exists但它只是混亂我的數組。

+0

一些明智的代碼縮進將是一個好主意。 它可以幫助我們閱讀代碼,更重要的是它可以幫助您調試代碼**。 [快速瀏覽編碼標準](http://www.php-fig.org/psr/psr-2/)爲您帶來的好處。 您可能會被要求在幾周/幾個月內修改此代碼,最後您會感謝我。 – GrumpyCrouton

回答

0

老實說,並沒有真正跟在這個問題上,並且與refs有點混淆。

你只是想做這樣的事情嗎?

<?php 

$ref = []; 
$items = []; 
$subCount = 0; 

foreach ($row as $row) { 
    $thisRef = &$ref[$row->id]; 
    $thisRef['parent_id'] = $row->parent_id; 
    $thisRef['menu_id'] = $row->menu_id; 
    $thisRef['type'] = $row->type; 
    $thisRef['id'] = $row->id; 
    if($row->parent_id == 0) { 
     $items[] = &$thisRef; 
    } else { 
     $subCount++; 
     $ref[$row->parent_id]['sub-' . $subCount][] = &$thisRef; 
    } 
} 
+0

它與我想要的相似,但它不是,我想檢查某個數組是否全部準備好了,並將其重命名爲sub 這樣的事情。 array [1] - > [sub] - > [0] - > [subofsub] –

+0

如果我們表示爲整數值,我們可以稱之爲'深度'是的?你熟悉遞歸的概念嗎?不確定我想嘗試使用您現有的代碼進行解釋。可能值得一讀這個話題?像這樣的帖子:https://stackoverflow.com/questions/10782810/echo-menu-tree-with-recursive-function – ficuscr