【问题标题】:MYSQL Parent Child Same Table; PHP Nest Children Within Parents as a Multidimensional-ArrayMYSQL父子同表; PHP 将子代嵌套在父代中作为多维数组
【发布时间】:2012-12-03 00:39:52
【问题描述】:

MYSQL 返回一个数组,如下所示。我正在使用 column: 'id_parent' 来自引用表以创建层次结构。因此,“id”为 2 的条目可以是任何“id_parent”为 2 的条目的父项,依此类推。

Array 
  (

    [1] => Array
        (
            [id] => 2
            [name] => About
            [id_parent] => NULL
        )

    [2] => Array
        (
            [id] => 4
            [name] => About Child
            [id_parent] => 2
        )

    [3] => Array
        (
            [id] => 5
            [name] => About Child's Child
            [id_parent] => 4
        )
  )

如何将子元素嵌套到其父数组中的数组中

Array
  (

    [1] => Array
        (
            [id] => 2
            [name] => About
            [id_parent] => 
            [children] => Array
                      (
                          [id] => 4
                          [name] => About Child
                          [id_parent] => 2
                          [children] => Array
                                    (
                                        [id] => 5
                                        [name] => About Child's Child
                                        [id_parent] => 4
                                    )
                      )
        )
  )

【问题讨论】:

    标签: php mysql arrays multidimensional-array mysqli


    【解决方案1】:

    引用,其优点是顺序无关紧要(子节点可以在其父节点之前):

     $tree = array('NULL' => array('children' => array()));
     foreach($array as $item){
        if(isset($tree[$item['id']])){
           $tree[$item['id']] = array_merge($tree[$item['id']],$item);
        } else {
           $tree[$item['id']] = $item;
        }
    
        $parentid = is_null($item['id_parent']) ? 'NULL' : $item['id_parent'];
        if(!isset($tree[$parentid])) $tree[$parentid] = array('children' => array());
        //this & is where the magic happens: any alteration to $tree[$item['id']
        //  will reflect in the item $tree[$parentid]['children'] as they are the same
        //  variable. For instance, adding a child to $tree[$item['id']]['children]
        //  will be seen in 
        //  $tree[$parentid]['children'][<whatever index $item['id'] has>]['children]
        $tree[$parentid]['children'][] = &$tree[$item['id']];
     }
     $result = $tree['NULL']['children'];
     //always unset references
     unset($tree);
    

    【讨论】:

    • 我现在要试试这个。感谢您的快速回复。
    • 第一次看时完全错过了那里的参考资料。很棒的小sn-p!
    • 完美!看到它的工作我很震惊。现在逐行剖析这个漂亮的款待。谢谢!
    • 哇,这是真正的交易。试图通过数组遍历数组映射数组减少来做到这一点,我变得太复杂了。这很简单,很有效,谢谢。
    猜你喜欢
    • 2015-09-02
    • 2020-09-26
    • 2015-10-28
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2016-12-12
    相关资源
    最近更新 更多