我的阵列:
array (
array(
['name'] => 'test1',
['level'] => 1
},
array(
['name'] => 'test2',
['level'] => 2
},
array(
['name'] => 'test3',
['level'] => 2
},
array(
['name'] => 'test4',
['level'] => 3
},
array(
['name'] => 'test5',
['level'] => 3
},
array(
['name'] => 'test6',
['level'] => 3
},
array(
['name'] => 'test7',
['level'] => 3
},
)
我想要的是什么:
________
| |
| test1 |
|________|
________ ________
| | | |
| test2 | | test3 |
|________| |________|
________ ________ ________ ________
| | | | | | | |
| test4 | | test5 | | test6 | | test7 |
|________| |________| |________| |________|
我已经有了按级别渲染的功能:
public static function f($rows)
{
$str = '';
$level = 0;
$first_li_mode = true;
foreach ($rows as $row) {
if ($level > $row['level']) {
$str .= '</li></ul>' . "\n";
$str .= '</li><li><a href="#">' . $row['name'] . '</a>' . "\n";
$first_li_mode = true;
} elseif ($row['level'] > $level) {
$str .= '<ul><li><a href="#">' . $row['name'] . '</a>' . "\n";
$first_li_mode = false;
;
} else {
if (!$first_li_mode) {
$str .= '</li>' . "\n";
} else {
$first_li_mode = false;
}
$str .= '<li><a href="#">' . $row['name'] . '</a>' . "\n";
}
$level = $row['level'];
}
while ($level > 0) {
$str .= '</li></ul>' . "\n";
$level--;
}
return $str;
}
它产生了什么:
<ul>
<li class="level_1">
<a href="#">
test1
</a>
<ul>
<li class="level_2">
<a href="">test2</a>
</li>
<li class="level_3">
<a href="">test3</a>
</li>
</ul>
</li>
</ul>
等等...,让我们说每个父母在这个列表中有2个孩子,问题是:如何设置这个列表的样式使它看起来像金字塔,使每个父节点(相对于孩子)出现在它们的顶部中间,如上图所示?无论深度级别如何,也许我需要在渲染函数中进行一些计算以使每个级别都进行偏移?但是如何?
答案 0 :(得分:0)
这就是我想要的。您可能需要稍微调整输出,看看它是否适合您。
$sorted_arr=array();
foreach ($arr as $a){
$sorted_arr[$a['level']][]=$a['name']
}
ksort($sorted_arr);
$css="";
foreach ($sorted_arr as $level => $s){
$count=count($s);
// First count the number of elements in each level.
$spacing=1/($count+1)*100-5;
// Get the percentage of the offset, then minus the 1/2 width of each li element ( say 10% )
$css.=".level_$level li {margin-left:".$spacing."%; width:10%} \n";
}
echo $css;