我有一个PHP数组,看起来像这样:
array (
[0] => array (
[id] => 1
[title] => "Title 1"
[parent_id] => NULL
[depth] => 0
)
[1] => array (
[id] => 2
[title] => "Title 2"
[parent_id] => NULL
[depth] => 0
)
[2] => array (
[id] => 3
[title] => "Title 3"
[parent_id] => 2
[depth] => 1
)
[3] => array (
[id] => 4
[title] => "Title 4"
[parent_id] => 2
[depth] => 1
)
[4] => array (
[id] => 5
[title] => "Title 5"
[parent_id] => NULL
[depth] => 0
)
[5] => array (
[id] => 6
[title] => "Title 6"
[parent_id] => 4
[depth] => 2
)
)
Run Code Online (Sandbox Code Playgroud)
我想要做的是迭代这个数组并<ol>从中创建一个嵌套列表.所以结果应该是这样的:
<ol>
<li>Title 1</li> // id = 1
<li>Title 2</li> // id = 2
<ol>
<li>Title 3</li> // id = 3 -> parent_id = 2
<li>Title 4</li> // id = 4 -> parent_id = 2
<ol>
<li>Title 6</li> // id = 6 -> parent_id = 4
</ol>
</ol>
<li>Title 5</li> // id = 5
</ol>
Run Code Online (Sandbox Code Playgroud)
我一直试图想办法如何完成这项工作.但到目前为止,每次尝试都失败
任何人都知道如何<ol>从这样的数组创建这样的嵌套列表?
请注意,我对给定数据没有任何控制权.我只是调用一个API,它返回json数据,我将其转换为数组.阵列看起来与我描述的完全一样.
dan*_*era 13
你应该使用递归:
首先是'php'语法中的数组:
<?php
$a=array (
'0' => array (
'id' => 1,
'title' => "Title 1",
'parent_id' => 'NULL',
'depth' => 0
),
'1' => array (
'id' => 2,
'title' => "Title 2",
'parent_id' => 'NULL',
'depth' => 0
),
'2' => array (
'id' => 3,
'title' => "Title 3",
'parent_id' => 2,
'depth' => 1
),
'3' => array (
'id' => 4,
'title' => "Title 4",
'parent_id' => 2,
'depth' => 1
),
'4' => array (
'id' => 5,
'title' => "Title 5",
'parent_id' => 'NULL',
'depth' => 0
),
'5' => array (
'id' => 6,
'title' => "Title 6",
'parent_id' => 4,
'depth' => 0
)
);
Run Code Online (Sandbox Code Playgroud)
这里的代码:
$level = 'NULL';
function r( $a, $level) {
$r = "<ol>";
foreach ( $a as $i ) {
if ($i['parent_id'] == $level ) {
$r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>";
}
}
$r = $r . "</ol>";
return $r;
}
print r( $a, $level );
?>
Run Code Online (Sandbox Code Playgroud)
该结果:
<ol><li>Title 1<ol></ol></li><li>Title 2<ol><li>Title 3<ol>
</ol></li><li>Title 4<ol><li>Title 6<ol></ol></li></ol></li></ol></li><li>Title 5
<ol></ol></li></ol>
Run Code Online (Sandbox Code Playgroud)
检查后作为解决方案编辑
为了避免空叶:
function r( $a, $level) {
$r = '' ;
foreach ( $a as $i ) {
if ($i['parent_id'] == $level ) {
$r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>";
}
}
return ($r==''?'':"<ol>". $r . "</ol>");
}
Run Code Online (Sandbox Code Playgroud)