Creating a nested UL from flat array in PHP

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-07 04:55:28

I would gather the data and construct a tree first, and then print the tree out. Some sample code:

foreach ($nodes as $item) {
    // gather the data in an assoc array indexed by id
    if ( !isset($data_by_id[ $item['top_id'] ])) {
        $data_by_id[ $item['top_id'] ] = array( 'name' => $item['standard'] );
    }
    if ( !isset($data_by_id[ $item['parent_id'] ])) {
        $data_by_id[ $item['parent_id'] ] = array( 'name' => $item['indicator'] );
    }
    if ( !isset($data_by_id[ $item['child_id'] ])) {
        $data_by_id[ $item['child_id'] ] = array( 
            'name' => $item['element'],
            'contents' => array(
                $item['Connections'],
                $item['Effective Practice'],
                $item['Proficient'],
                $item['Suggested Artifacts'])
        );
    }
    // construct the tree - I've made a simple three tier array
    $tree[ $item['top_id'] ][ $item['parent_id'] ][ $item['child_id'] ]++;
}

// go through the tree and print the info
// this is a recursive function that can be used on arbitrarily deep trees
function print_tree( $data, $arr ){
    echo "<ul>\n";
    // the tree is an associative array where $key is the ID of the node,
    // and $value is either an array of child nodes or an integer.
    foreach ($arr as $key => $value) {
        echo "<li>" . $data[$key]['name'] . "</li>\n";
        if (isset($data[$key]['contents']) && is_array($data[$key]['contents'])) {
            echo '<ul>';
            foreach ($data[$key]['contents'] as $leaf) {
                echo '<li>' . $leaf . "</li>\n";
            }
            echo "</ul>\n";
        }
        // if $value is an array, it is a set of child nodes--i.e. another tree.
        // we can pass that tree to our print_tree function.
        if (is_array($value)) {
            print_tree($data, $value);
        }
    }
    echo "</ul>\n";
}

print_tree($data_by_id, $tree);

You'll need to add in error checking, zapping of strange characters, removal of excess whitespace, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!