我们常常碰到需要构建树结构展示的情况,我推荐使用zTree和JSON。
例如:
<?php /** * * 使用zTree和json构建树节点 * */ $arr = array( 0=>array( 'id' => 1, 'pid' => 0, 'name' => 'china', 'son' => array( array( 'id' => 3, 'pid' => 1, 'name' => 'Beijing', ), array( 'id' => 5, 'pid' => 1, 'name' => 'Nanjing', 'son' => array( array( 'id' => 7, 'pid' => 1, 'name' => 'Jiangning', ) ), ), ), ), 1=>array( 'id' => 2, 'pid' => 0, 'name' => 'USA', 'son' => array( array( 'id' => 4, 'pid' => 2, 'name' => 'Washington', ), array( 'id' => 6, 'pid' => 2, 'name' => 'New York', ), ), ), ); function json_string($arr){ echo(str_replace("son","children",json_encode($arr)));//zTree中下级用children表示,json_encode只支持utf-8编码 } json_string($arr); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML4.01//EN" "http://www.w3.org/TR/html4/strict.dtd”> <HTML> <HEAD> <TITLE> ZTREE DEMO </TITLE> <meta http-equiv="content-type" content="text/html; charset=gb2312"> <link rel="stylesheet" href="../css/zTreeStyle/zTreeStyle.css" type="text/css"> <script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="../js/jquery.ztree.all-3.5.min.js"></script> <script type="text/javascript"> function zTreeInit() { var zTreeObj; var setting = {}; var zNodes = eval(<?php json_string($arr) ?> ); zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes); } $(document).ready(function () { zTreeInit(); }); </script> </HEAD> <BODY> <div> <ul id="treeDemo" class="ztree"></ul> </div> </BODY> </HTML>
原文地址:http://blog.csdn.net/bubu8633/article/details/40893735