2017-07-26 2 views
0

多次元配列に関する質問があります。アレイの形成

私は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 
     ) 
    ) 
) 

、その良いが、私は、配列のすべての準備がサブを持っている場合、私が意味する第二の配列のキーのサブの名前を変更したいのですが、第2のサブはsubofsubされるだろう、私はそれをチェックしてみました、私はそれをよく説明願っていますissetとarray_key_existsを使用していますが、配列が乱れてしまいます。

+0

適切なコードインデントがあるとよいでしょう。 このコードを読むと、コードをデバッグするのに役立ちます**。 [コーディング標準を素早く見てください](http://www.php-fig.org/psr/psr-2/)を参考にしてください。 このコードを数週間/数ヶ月で修正するように求められ、最終的に私に感謝します。 – GrumpyCrouton

答えて

0

正直言って本当に質問に従わず、少し参考になると混乱します。

あなたは単にこのようなことをしようとしていますか?

<?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

それは私が望むものと似ていますが、配列がすべて準備ができているかどうかチェックしたいのですが、そのサブはサブの名前に変更されています このようなものです。 array [1] - > [sub] - > [0] - > [subofsub] –

+0

整数値として「深さ」と呼ぶことができますか?あなたは再帰の概念に精通していますか?私はあなたの既存のコードを使って説明しようとします。トピックについていくつか読む価値がありますか?投稿は次のとおりです:https://stackoverflow.com/questions/10782810/echo-menu-tree-with-recursive-function – ficuscr

関連する問題