PHP Array to jsTree

好久不见. 提交于 2019-12-06 15:02:36

Creating jsTree from Array

First, let's tackle how to turn an array in to something jsTree will play nicely with, since json_encode doesn't work properly, we'll result to an unordered list format. Since the input array can contain either scalar data or an array, it will need to be recursive.

For this, we'll create the array2jstree function, which essentially turns the array in to an unordered list that is not specific to jsTree with one class exception.

function array2jstree($ar){
    $out = '';
    foreach($ar as $k => $v){
        $out .= "<li>$k";
        if(is_array($v)){
            $out .= array2jstree($v);
        }else{
            $out .= "<ul><li class=\"jstree-nochildren\">$v</li></ul>";
        }
        $out .= '</li>';
    }
    return "<ul>$out</ul>";
}

What this does is goes through each element in the array and, if another array, calls itself and creates an unordered list underneath the 'parent' <li> element, if not an array, still expands to a new list, but it only contains the value. In this way, an array of:

array(
    'data' => 'value'
)

Will be expanded upon data showing value as it's child.

Note the class for the non-array value, being jstree-nochildren. This class is not part of jsTree, but is being used for any item that has no children (so the icon can be removed successfully.)

Now, all that is needed is to drop the function in, and pass an array to it for a nice working jsTree, with icons. Putting it together to show how to use it would be (using echo as an example, but can easily be pass as a variable to a templating engine, etc:

echo '<div id="cTree">'. array2jstree(array('name' => $myArray)) .'</div>';

The reason to pass a new array to the function is so that it has a defined 'root' node to expand, omit it if you don't need a root node.

And the JS to initialize it as a jsTree:

    <script>
    $('#cTree').jstree();
    </script>

Now you have a drop-in function to convert arrays to a jsTree! Now, back to the issue of no icon for nodes that have no children, we will create a style based on that class we assigned earlier jstree-nochildren, and working with what jsTree converts the list to, the only style you need to add is:

.jstree-nochildren > a > .jstree-icon { display:none !important; } 

Now you are all done!

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