我有表类别
如何创建第二级菜单insertfunction
(rodzic表示父级)
答案 0 :(得分:0)
假设您在数组中有数据:
$data = [
['id' => 3, 'typ' => 'kategorie', 'rodzic' => 0, 'nazwa' => 'OFERTA'],
['id' => 5, 'typ' => 'kategorie', 'rodzic' => 3, 'nazwa' => 'Kominki na drewno'],
/* more elements here */
];
您可以先处理数组并从中获取两个数组:顶级元素数组和子元素数组:
$top_level = [];
$sub_elem = [];
foreach($data as $row) {
$rd = $row['rodzic'];
if($rd) { // has parent
if(!isset($sub_elem[$rd])) { // first time encounter, initialize array
$sub_elem[$rd] = [];
}
$sub_elem[$rd][] = $row; // append row
}
else {
$top_level[] = $row; // append top level row
}
}
然后你只需迭代这样的数据:
<ul>
<?php foreach($top_level as $row): ?>
<li>
<?php echo $row['nazwa'] ?>
<?php if(isset($sub_elem[$row['id']])): ?>
<ul>
<?php foreach($sub_elem[$row['id']] as $sub_row): ?>
<li><?php echo $sub_row['nazwa'] ?></li>
<?php endforeach ?>
</ul>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
这只适用于一个深度。要对列表进行任意嵌套,您需要创建一个recursive函数,我将其作为练习留给读者。