數(shù)組結(jié)構(gòu)是這樣的:
然后組裝成html結(jié)構(gòu)的方法如下:
function creatHtmlTree($tree)
{
static $htmlTree;
$htmlTree .= '<ul>';
foreach ($tree as $key => $value) {
$htmlTree .= "<li><span><i class='icon-folder-open'></i>{$value['name']} </span> <a href=''>Goes somewhere</a>";
if (isset($value['childs']) && is_array($value['childs'])) {
$html = creatHtmlTree($value['childs']);
$htmlTree .= $html;
}
$htmlTree .= "</li>";
}
$htmlTree .= "</ul>";
return $htmlTree;
}
但是實際上輸出的結(jié)果是錯誤的:
自己猜想,一定是自己的遞歸邏輯有問題,但是實在是想不明白問題到底出在哪里。所以還請幫忙看下,那段遞歸代碼有什么問題
另外貼出完整的測試代碼:
<?php
$data[] =array('id'=>1,'parentid'=>0,'name'=>'中國');
$data[] =array('id'=>2,'parentid'=>0,'name'=>'美國');
$data[] =array('id'=>3,'parentid'=>0,'name'=>'韓國');
$data[] =array('id'=>4,'parentid'=>1,'name'=>'北京');
$data[] =array('id'=>5,'parentid'=>1,'name'=>'上海');
$data[] =array('id'=>6,'parentid'=>1,'name'=>'廣西');
$data[] =array('id'=>7,'parentid'=>6,'name'=>'桂林');
$data[] =array('id'=>8,'parentid'=>6,'name'=>'南寧');
$data[] =array('id'=>9,'parentid'=>6,'name'=>'柳州');
$data[] =array('id'=>10,'parentid'=>2,'name'=>'紐約');
$data[] =array('id'=>11,'parentid'=>2,'name'=>'華盛頓');
$data[] =array('id'=>12,'parentid'=>3,'name'=>'首爾');
/**格式化數(shù)組輸出**/
function p($arr)
{
echo "<pre>";
echo '========================開始========================';
echo "</br>";
if( $arr ){
print_r($arr);
} else {
echo '此值為空';
}
echo "</br>";
echo '========================結(jié)束========================';
echo "</pre>";
}
/**
* 多維數(shù)組樹形結(jié)構(gòu)
*/
function tree($data, $pid = 0)
{
// static $html = '';
// $html .= '<ul>';
$children = [];
// p($data);
foreach ($data as $key => $value) {
if ($value['parentid'] == $pid) {
// $html .= '<li>';
$children[] = $value;
}
}
if (empty($children)) {
return null;
}
foreach ($children as $key => $value) {
$chid = tree($data, $value['id']);
if ($chid != null) {
$children[$key]['childs'] = $chid;
}
}
// $html .= '</ul>';
return $children;
}
function creatHtmlTree($tree)
{
static $htmlTree;
$htmlTree .= '<ul>';
foreach ($tree as $key => $value) {
$htmlTree .= "<li><span><i class='icon-folder-open'></i>{$value['name']} </span> <a href=''>Goes somewhere</a>";
if (isset($value['childs']) && is_array($value['childs'])) {
$html = creatHtmlTree($value['childs']);
$htmlTree .= $html;
}
$htmlTree .= "</li>";
}
$htmlTree .= "</ul>";
return $htmlTree;
}
$tree = tree($data);
$htmlTree = creatHtmlTree($tree);
p($tree);
p($htmlTree);
1 回答

慕仙森
TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
解決了。creatHtmlTree()
方法中把static $htmlTree
去掉就可以了;
完整版函數(shù):
function creatHtmlTree($tree)
{
$htmlTree = '<ul>';
foreach ($tree as $key => $value) {
$htmlTree .= "<li><span><i class='icon-folder-open'></i>{$value['name']} </span> <a href=''>Goes somewhere</a>";
if (isset($value['childs']) && is_array($value['childs'])) {
$html = creatHtmlTree($value['childs']);
$htmlTree .= $html;
}
$htmlTree .= "</li>";
}
$htmlTree .= "</ul>";
return $htmlTree;
}
- 1 回答
- 0 關(guān)注
- 558 瀏覽
添加回答
舉報
0/150
提交
取消