-1

我想用递归函数构建项目树......(<ul><li>)有人可以帮助我吗?我怎样才能在这个阵列上运行?例如...

我使用 Codeigniter 如果它改变了任何东西......

Array
(
    [0] => stdClass Object
        (
            [id] => 1000
            [children] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 1001
                            [children] => Array
                                (
                                    [0] => stdClass Object
                                        (
                                            [id] => 1002
                                        )

                                )

                        )

                )

        )

    [1] => stdClass Object
        (
            [id] => 1003
            [children] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 1004
                        )

                )

        )

)

输出需要是这样的:

<div class="dd">
    <ol class="dd-list">
        <li class="dd-item" data-id="1000">
            <div class="dd-handle">parent 1000</div>
            <ol class="dd-list">
                <li class="dd-item" data-id="1001">
                    <div class="dd-handle">children of 1000 and parent of 1002</div>
                    <ol class="dd-list">
                        <li class="dd-item" data-id="1002">
                            <div class="dd-handle">children of 1001</div>
                        </li>
                    </ol>
                </li>
            </ol>
        </li>
        <li class="dd-item" data-id="1003">
            <div class="dd-handle">parent 1003</div>
            <ol class="dd-list">
                <li class="dd-item" data-id="1004">
                    <div class="dd-handle">children of 1003</div>
                </li>
            </ol>
        </li>
    </ol>
</div>
4

1 回答 1

0

这应该可以解决问题:

function render(array $children) {
    echo '<ol class="dd-list">';
    foreach($children as $child) {
        echo '<li class="dd-item" data-id="', $child->id, '">';
        echo '<div class="dd-handle">parent ', $child->id, '</div>';
        if(isset($child->children)) {
            render($child->children);
        }
        echo '</li>';
    }
    echo '</ol>';
}

echo '<div class="dd">';
render($array);
echo '</div>';
于 2013-09-26T23:03:18.400 回答