PHP数组无限分级层级处理的解决办法
内容摘要
这篇文章主要为大家详细介绍了PHP数组无限分级层级处理的简单示例,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随php教程的小玲来看看吧!
代码如下:
感兴趣的小伙伴,下面一起跟随php教程的小玲来看看吧!
代码如下:
文章正文
这篇文章主要为大家详细介绍了PHP数组无限分级层级处理的简单示例,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随php教程的小玲来看看吧!
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <code> /** * 创建父节点树形数组 * 参数 * $ar 数组,邻接列表方式组织的数据 * $id 数组中作为主键的下标或关联键名 * $pid 数组中作为父键的下标或关联键名 * 返回 多维数组 **/ function find_parent( $ar , $id = 'id' , $pid = 'pid' ) { foreach ( $ar as $v ) $t [ $v [ $id ]] = $v ; foreach ( $t as $k => $item ){ if ( $item [ $pid ] ){ if ( ! isset( $t [ $item [ $pid ]][ 'parent' ][ $item [ $pid ]]) ) $t [ $item [ $id ]][ 'parent' ][ $item [ $pid ]] =& $t [ $item [ $pid ]]; $t [ $k ][ 'reference' ] = true; } } return $t ; } /** * 创建子节点树形数组 * 参数 * $ar 数组,邻接列表方式组织的数据 * $id 数组中作为主键的下标或关联键名 * $pid 数组中作为父键的下标或关联键名 * 返回 多维数组 **/ function find_child( $ar , $id = 'id' , $pid = 'pid' ) { foreach ( $ar as $v ) $t [ $v [ $id ]] = $v ; foreach ( $t as $k => $item ){ if ( $item [ $pid ] ) { $t [ $item [ $pid ]][ 'child' ][ $item [ $id ]] =& $t [ $k ]; $t [ $k ][ 'reference' ] = true; } } return $t ; } </code> |
代码如下:
1 2 3 4 5 6 7 8 9 10 | <code> $data = array ( array ( 'ID' =>1, 'PARENT' =>0, 'NAME' => '祖父' ), array ( 'ID' =>2, 'PARENT' =>1, 'NAME' => '父亲' ), array ( 'ID' =>3, 'PARENT' =>1, 'NAME' => '叔伯' ), array ( 'ID' =>4, 'PARENT' =>2, 'NAME' => '自己' ), array ( 'ID' =>5, 'PARENT' =>4, 'NAME' => '儿子' ) ); $p = find_parent( $data , 'ID' , 'PARENT' ); $c = find_child( $data , 'ID' , 'PARENT' ); </code> |
代码如下:
1 2 3 4 5 6 7 8 9 | <code> foreach ( $p as $key => $item ) { if ( $item [ 'reference' ]) continue ; print_r( $item ); } foreach ( $c as $key => $item ) { if ( $item [ 'reference' ]) continue ; print_r( $item ); } </code> |
代码如下:
1 2 3 4 5 6 7 8 9 10 11 | <code> $mylist = array ( array ( 'parent_id' =>0, 'id' =>1), array ( 'parent_id' =>0, 'id' =>2), array ( 'parent_id' =>0, 'id' =>3), array ( 'parent_id' =>2, 'id' =>4), array ( 'parent_id' =>2, 'id' =>5), array ( 'parent_id' =>3, 'id' =>6), array ( 'parent_id' =>3, 'id' =>7), array ( 'parent_id' =>4, 'id' =>8), array ( 'parent_id' =>5, 'id' =>9), array ( 'parent_id' =>5, 'id' =>10) );</code> |
function _findChildren($list, $p_id){ //数据层级化, $r = array(); foreach($list as $id=>$item){ if($item['parent_id'] == $p_id) { $length = count($r); $r[$length] = $item; if($t = $this->_findChildren($list, $item['id']) ){ $r[$length]['children'] = $t; } } } return $r; }
print_r(_findChildren($mylist, 0));
注:关于PHP数组无限分级层级处理的简单示例的内容就先介绍到这里,更多相关文章的可以留意
代码注释