gpt4 book ai didi

php - 如何从 PHP 中的类别字符串创建嵌套类别列表

转载 作者:行者123 更新时间:2023-11-29 03:03:58 25 4
gpt4 key购买 nike

我有一个 MySQL 表“products”,其中有一列名为“category”。在此字段中,您可以找到每个产品的类别层次结构作为字符串。例如:

female / dresses / long
female / dresses / short
female / shoes
male / shoes / sneakers / skate
...

我选择了所有不同的类别:

$result = $mysqli->query("SELECT DISTINCT category FROM products ORDER BY category");

现在,我希望能够将这些类别打印为嵌套的 HTML 列表

    • 连衣裙
    • 鞋子
    • 鞋子
      • 运动鞋
        • 滑冰

如有任何建议,我们将不胜感激。谢谢!

编辑:我从几个 csv 文件中获取数据,因此不需要转换类别的解决方案会很棒!

最佳答案

只需使用类别作为节点的关键字来构建您的树。例如:

$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>

关于php - 如何从 PHP 中的类别字符串创建嵌套类别列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18706007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com