将内联父子关系转换为分层树?

时间:2017-11-27 06:40:01

标签: php arrays

如果category_id = 0元素是父元素。父元素由category_id定义。如果category_id不等于零,则它具有父元素。如何在php中制作变换器的递归函数? 我有阵列:

$tree = ([
    [
        'id' => 1,
        'text' => 'Parent 1',
        'category_id' => 0
    ],
    [
        'id' => 2,
        'text' => 'Parent 2',
        'category_id' => 0
    ],
    [
        'id' => 3,
        'text' => 'Child 1',
        'category_id' =>  1
    ],
    [
        'id' => 4,
        'text' => 'Child 2',
        'category_id' => 3
    ],
    [
        'id' => 5,
        'text' => 'Parent',
        'category_id' => 0
    ],
    [
        'id' => 6,
        'text' => 'Child 3',
        'category_id' => 5
    ]
]);

如何以这种形式生成树:

$tree_new = [
    {
        'id': 1,
        'text': 'Parent 1',
        'category_id': 0,
        'children': {
            'id': 3,
            'text': 'Child 1',
            'category_id': 1,
            'children': {
                'id': 4,
                'text': 'Child 2',
                'category_id': 3
            },
        },
    },
    {
        'id': 2,
        'text': 'Parent 2',
        'category_id': 0
    },
    {
        'id': 5,
        'text': 'Parent',
        'category_id': 0,
        'children': {
            'id': 6,
            'text': 'Child 3',
            'category_id': 5
        }
    }
];

我试过了:

function createTree($tree, $root = null) {
    $return = array();
    foreach($tree as $child => $parent) {
        if($parent == $root) {
            unset($tree[$child]);
            $return[] = array(
                'children' => parseTree($tree, $child)
            );
        }
    }
    return empty($return) ? null : $return;    
}

$tree = ([
    [
        'id' => 1,
        'text' => 'Parent 1',
        'category_id' => 0
    ],
    [
        'id' => 2,
        'text' => 'Parent 2',
        'category_id' => 0
    ],
    [
        'id' => 3,
        'text' => 'Child 1',
        'category_id' =>  1
    ],
    [
        'id' => 4,
        'text' => 'Child 2',
        'category_id' => 3
    ],
    [
        'id' => 5,
        'text' => 'Parent',
        'category_id' => 0
    ],
    [
        'id' => 6,
        'text' => 'Child 3',
        'category_id' => 5
    ]
]);
$new_tree = createTree($tree);
var_dump($tree);
var_dump($new_tree);

0 个答案:

没有答案