0

If the category_id = 0 element is a parent element. Parent element is defined by category_id. If category_id is not equal to zero, then it has a parent element. How to make the recursive function of a transformer in php? I have array:

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

How can I generate a tree in this form:

$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
        }
    }
];

I tried that:

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 Answers0