2013-01-14 17 views
-1

我有一個數組,我想順序重新安排父母給孩子。這裏在我的數組中得到了值'parent_table'的唯一值'table_id'&。因此,parent_table將檢查是否存在任何'table_id'。如果存在,它將在'table_id'下。下面是代碼:如何安排一個數組,如菜單順序

Array 
(
[0] => Array 
(
[table_id] => 7 
[table_name] => Macro 
[parent_table] => 1 
) 
[1] => Array 
(
[table_id] => 4 
[table_name] => Dise 
[parent_table] => 7 
) 
[2] => Array 
(
[table_id] => 5 
[table_name] => Cox 
[parent_table] => 7 
) 
[3] => Array 
(
[table_id] => 6 
[table_name] => Ripo 
[parent_table] => 4 
) 
) 

樣本輸出:

Array 
     (
     [1] => Array 
        (
        [table_id] => 7 
        [table_name] => Macro 
        [parent_table] => 1 
        [7] => Array 
           (
           [table_id] => 4 
           [table_name] => Dise 
           [parent_table] => 7 
           [4] => Array 
              (
              [table_id] => 6 
              [table_name] => Ripo 
              [parent_table] => 4 
              ) 
           ) 
        [7] => Array 
           (
           [table_id] => 5 
           [table_name] => Cox 
           [parent_table] => 7 
           ) 
       ) 
) 

請提供一些想法,因爲我很新的PHP。

+1

(HTTP:// WWW。 whathaveyoutried.com/) – Peon

+0

檢查這個帖子http://stackoverflow.com/questions/7563439/php-recursive-function-for-building-array-from-tree –

回答

1

您還可以使用兩個foreach循環和references

// Build a new array, with nodes indexed by table_id 
$byID = array(); 
foreach ($arr as $node) { 
    $byID[$node['table_id']] = $node; 
} 

// Append child nodes to their parents' child_tables arrays 
foreach ($byID as &$node) { 
    if (isset($node['parent_table'])) { 
     $byID[$node['parent_table']]['child_tables'][] =& $node; 
    } 
} 

那麼整個樹是由$byID[1]表示:?你嘗試過什麼]

Array 
(
    [child_tables] => Array 
     (
      [0] => Array 
       (
        [table_id] => 7 
        [table_name] => Macro 
        [parent_table] => 1 
        [child_tables] => Array 
         (
          [0] => Array 
           (
            [table_id] => 4 
            [table_name] => Dise 
            [parent_table] => 7 
            [child_tables] => Array 
             (
              [0] => Array 
               (
                [table_id] => 6 
                [table_name] => Ripo 
                [parent_table] => 4 
               ) 

             ) 

           ) 

          [1] => Array 
           (
            [table_id] => 5 
            [table_name] => Cox 
            [parent_table] => 7 
           ) 

         ) 

       ) 

     ) 

) 
相關問題