只需使用类别作为节点的键来构建您的树。例如 :
$categoryLines = array(
"female / dresses / long",
"female / dresses / short",
"female / shoes",
"male / shoes / sneakers / skate"
);
function buildCategoryTree($categoryLines, $separator) {
$catTree = array();
foreach ($categoryLines as $catLine) {
$path = explode($separator, $catLine);
$node = & $catTree;
foreach ($path as $cat) {
$cat = trim($cat);
if (!isset($node[$cat])) {
$node[$cat] = array();
}
$node = & $node[$cat];
}
}
return $catTree;
}
function displayCategoryTree($categoryTree, $indent = '') {
foreach ($categoryTree as $node => $children) {
echo $indent . $node . "\n";
displayCategoryTree($children, $indent . '|- ');
}
}
$categoryTree = buildCategoryTree($categoryLines, '/');
现在,var_export($categoryTree)
将输出:
array (
'female' => array (
'dresses' => array (
'long' => array (),
'short' => array (),
),
'shoes' => array (),
),
'male' => array (
'shoes' => array (
'sneakers' => array (
'skate' => array (),
),
),
),
)
并将displayCategoryTree($categoryTree)
输出:
female
|- dresses
|- |- long
|- |- short
|- shoes
male
|- shoes
|- |- sneakers
|- |- |- skate
** 编辑 **
获取树的 HTML 表示:
function displayHtmlCategoryTree($categoryTree, $id = null, $pathSeparator = '/', $parents = '') {
if (empty($categoryTree)) return '';
$str = '<ul' . (!empty($id) ? ' id="'.$id.'"' : '') . '>';
foreach ($categoryTree as $node => $children) {
$currentPath = $parents . (empty($parents) ? '' : $pathSeparator) . $node;
$str .= '<li title="' . $currentPath . '">' . $node .
displayHtmlCategoryTree($children, null, $pathSeparator, $currentPath) .
'</li>';
}
$str .= '</ul>';
return $str;
}
echo displayHtmlCategoryTree($categoryTree, "test", ' / ');
并将输出:
<ul id="test"><li title="female">female<ul><li title="female / dresses">dresses<ul><li title="female / dresses / long">long</li><li title="female / dresses / short">short</li></ul></li><li title="female / shoes">shoes</li></ul></li><li title="male">male<ul><li title="male / shoes">shoes<ul><li title="male / shoes / sneakers">sneakers<ul><li title="male / shoes / sneakers / skate">skate</li></ul></li></ul></li></ul></li></ul>