2017-07-26 70 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