我对嵌套数组有一个很大的问题,它包含类别树:
Array(
[1] => Array
(
[parent_id] => 0
[category_id] => 1
[name] => Auto-moto
[path] => Auto-moto
[children] => Array
(
[4] => Array
(
[parent_id] => 1
[category_id] => 4
[name] => Autodiely
[path] => Auto-moto/Autodiely
[children] => Array
(
[5] => Array
(
[parent_id] => 4
[category_id] => 5
[name] => Kabínové filtre pre automobily
[path] => Auto-moto/Autodiely/Kabínové filtre pre automobily
[children] =>
)
我有一个递归函数在html ul>中显示它li列表,但我想使列表看起来像这样:
1.Auto-moto
1.1.Autodiely
1.1.1.Kabínové filtre pre automobily
1.1.2. xxxx
1.2.YYY
1.3.AAA
2.New
2.1.Sub....
这可能吗?非常感谢您的帮助。
答案 0 :(得分:1)
使用递归。我的方法是递归地遍历所有级别的整个数组,并且对于每个级别将相应的代码添加到“级别”键中。 这是一个例子:
$arr = array(
'a' => array(
'name' => 'a',
'children' => array(
'aa' => array(
'name' => 'aa',
'children' => array(
'aaa' => array(
'name' => 'aaa',
),
),
),
'ab' => array(
'name' => 'ab',
'children' => array(
'aba' => array(
'name' => 'aba',
'children' => array(
'abaa' => array(
'name' => 'abaa',
),
),
),
'abb' => array(
'name' => 'abb',
),
),
),
)
),
'b' => array(
'name' => 'b',
'children' => array(
'ba' => array(
'name' => 'ba',
),
'bb' => array(
'name' => 'bb',
),
)
),
);
/**
* To target array, for each level adds new field named 'level', with level deep number
* @param type $array target array
* @param type $level nested level number
*/
function add_levels( &$array, $level ){
$i = 0;
foreach ( $array as $key => &$value ) {
$level_name = $level.++$i;
$value[ 'level' ] = $level_name;
if( array_key_exists( 'children', $value ) and is_array( $value[ 'children' ] )){
add_levels( $value[ 'children' ], $level_name.'.' );
}
}
}
/**
* Prints out array in required form
* @param type $array
*/
function draw_ordered( $array ){
foreach ( $array as $key => &$value ) {
echo( $value[ 'level' ].'.'. $value[ 'name' ].'<br />' );
if( array_key_exists( 'children', $value ) and is_array( $value[ 'children' ] )){
draw_ordered( $value[ 'children' ] );
}
}
}
add_levels( $arr );
//print_r($arr);
draw_ordered( $arr );
die();