0

MYSQLは、以下に示すような配列を返します。列'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
                                    )
                      )
        )
  )
4

1 に答える 1

12

順序が重要ではないという利点を持つ参照(子ノードは親ノードの前に来ることができます):

 $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);
于 2012-12-15T01:33:38.850 に答える