PHP数组分级,万般无奈,救助
array (
array("level" => '1', "caption" => "一级菜单1"),
array("leve1" => '1', "caption" => "一级菜单2"),
array("leve1" => '2', "caption" => "二级菜单1"),
array("leve1" => '2', "caption" => "二级菜单2"),
array("leve1" => '1', "caption" => "一级菜单3"),
)
其中level = 2为其上方最近leve1 = 1 的子菜单,不排除会有level = 3的子菜单(从属于level = 2)现在想弄成下面的形式,想了好久也没什么好方法,同事建议我用递归,可递归小弟不太懂,PHP初接触,给各位大拿添麻烦了
array (
array("level" => '1', "caption" => "一级菜单1"),
array("leve1" => '1', "caption" => "一级菜单2",
"sub"=>array("leve1" => '2', "caption" => "二级菜单1"),
"sub"=>array("leve1" => '2', "caption" => "二级菜单2")
),
array("leve1" => '1', "caption" => "一级菜单3"),
)
php?菜单?递归
------解决方案--------------------你连搜索搜不会,怎么查资料做IT啊?
搜“php 无限分类”
http://bbs.csdn.net/topics/360028778
http://bbs.csdn.net/topics/250025103
http://bbs.csdn.net/topics/320022124
……
你的数组里面
level 相当于 pid(把=1改为=0)
caption 拆分为 id 和 name
照着上面抄吧,先完成了,有空自己再理解人家的递归方法
偶忙着做其他事情
------解决方案--------------------参考下我写的
$arr = array(
array('id'=>1,'city_name'=>'中国','rel_id'=>'1','pid'=>0),
array('id'=>2,'city_name'=>'广东','rel_id'=>'1-2','pid'=>1),
array('id'=>3,'city_name'=>'深圳','rel_id'=>'1-2-3','pid'=>2),
array('id'=>4,'city_name'=>'广州','rel_id'=>'1-2-4','pid'=>2)
);
function find_subclass( $pid ){
global $arr;
$__arr = array();
foreach ( $arr as $k=>$v )
{
if( $v['pid']==$pid )$__arr[] = $v;
}
return $__arr;
}
function tree_subclass($pid=0){
$__arr = array();
$__arr = find_subclass($pid);
if( !empty($__arr) ){
foreach ( $__arr as $k=>$v )
{