传递数组的正确方法

时间:2019-12-15 06:39:35

标签: php wordpress woocommerce tree categories

这让我感到困惑,因为我认为代码是正确的,但是没有点击,这是我从Yanick Rochon那里挑选的代码,当数组经过硬编码时(在注释掉的区域中)它可以工作但是,当我从所有pa_mymelp术语中将数组推到一起时,它的表现却不尽人意,它将整个行作为一个项目使用,而不是每行使用多个项目,并且也没有创建子项,请问为什么..谢谢!:

    <?php
$thearray = array();
$terms = get_terms("pa_mymelp");
foreach ( $terms as $term ) {
$categories =  $term->name;
array_push($thearray, $categories);
}

$categoryLines = $thearray;

/*$categoryLines = array(
    "Dodge>2002>Ram 3500>5.9 359cid L6 DIESEL OHV>Engine>Engine Oil Cooler",
    "Dodge>2001>Ram 2500>5.9 359cid L6 DIESEL OHV>Engine>Engine Oil Cooler"
);*/


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, '>');

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", '>');
?>

0 个答案:

没有答案