MYSQL 父子同表;PHP 将父级中的子级嵌套为多维数组 [英] MYSQL Parent Child Same Table; PHP Nest Children Within Parents as a Multidimensional-Array

查看:27
本文介绍了MYSQL 父子同表;PHP 将父级中的子级嵌套为多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

MYSQL returns an array as shown below. I am using column: 'id_parent' to self reference the table to create hierarchy. So an entry with an 'id' of 2 can be the parent of any entry with a 'id_parent' of 2, and so on.

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

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

How can I nest the children into an array within their parent array

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

推荐答案

参考文献,具有顺序无关紧要的优点(子节点可以在其父节点之前):

References, with the advantages that order doesn't matter (childnodes can come before their parentnodes):

 $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);

这篇关于MYSQL 父子同表;PHP 将父级中的子级嵌套为多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆