PHP实现从分号分隔字符串动态生成带嵌套optgroup的下拉选择框
无限层级嵌套select生成方案
实现逻辑
首先将所有分号分隔的分类字符串转换为嵌套树形结构,再通过递归遍历树形结构生成对应层级的optgroup和option标签,天然支持无限层级扩展,不需要固定层级判断。
完整PHP实现代码
<?php // 原始输入数组 $categories = [ "mobili;tavolini_lato_divano", "mobili;tavoli_da_pranzo", "illuminazione;plafoniere", "illuminazione;lampade_decorative", "sculture;sculture_in_resina", "sculture;sculture_in_resina;serie_limitata_tatoo", "sculture;sculture_in_resina;sculture_resina_grandi", ]; // 1. 构建嵌套树形结构 $tree = []; foreach ($categories as $item) { $segments = explode(';', $item); $currentNode = &$tree; $segCount = count($segments); foreach ($segments as $idx => $seg) { $isLeaf = $idx === $segCount - 1; if (!isset($currentNode[$seg])) { $currentNode[$seg] = [ 'is_leaf' => $isLeaf, 'children' => [] ]; } $currentNode = &$currentNode[$seg]['children']; } } // 2. 递归生成select内容 function buildSelectHtml($nodes, $indentLevel = 0) { $html = ''; $indent = str_repeat(' ', $indentLevel); foreach ($nodes as $name => $node) { // 格式化显示文本:下划线转空格,首字母大写 $displayText = ucwords(str_replace('_', ' ', $name)); if ($node['is_leaf']) { $html .= "{$indent}<option value=\"{$name}\">{$displayText}</option>\n"; } else { $html .= "{$indent}<optgroup label=\"{$displayText}\">\n"; $html .= buildSelectHtml($node['children'], $indentLevel + 1); $html .= "{$indent}</optgroup>\n"; } } return $html; } // 输出最终select echo '<select name="product_category">'; echo buildSelectHtml($tree); echo '</select>'; ?>
输出效果说明
生成的HTML完全符合嵌套要求:
- 分割后2段的内容:第一段作为一级
optgroup,第二段作为该分组下的option - 分割后3段的内容:第二段作为一级
optgroup下嵌套的二级optgroup,第三段作为二级分组下的option - 分割段数超过3的内容会自动生成对应层级的嵌套
optgroup,无层级上限
内容的提问来源于stack exchange,提问作者Tilen
相关产品推荐
相关产品推荐

