カテゴリをノードのキーとして使用してツリーを構築するだけです。例えば :
$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>