MYSQL Parent Child Same Table; PHP Nest Children Within Parents as a Multidimensional-Array

前端 未结 1 1663
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 14:20

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

相关标签:
1条回答
  • 2020-12-09 15:03

    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);
    
    0 讨论(0)
提交回复
热议问题