0

This one is boggling me, because I think the code is right but something just isn't clicking, this is a code I picked up from Yanick Rochon and it works when the array is hard coded (in the commented out area) but when I push together the array from all of the pa_mymelp terms it doesn't behave as expected, it uses the entire line as an item vs multiple items per line, and does not create children either, wonder why.. thank you!:

    <?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", '>');
?>
  • run `var_dump($categoryLines)` to ensure it contains what you think it contains. – Alex Howansky Dec 15 '19 at 06:44
  • Check these two posts your question : `https://stackoverflow.com/questions/49732477/php-bootstrap-4-navigation-menu-with-sub-menus/53892122` and alternatives : https://stackoverflow.com/questions/35527414/build-a-bootstrap-drop-down-multi-level-menu-from-a-php-array –  Dec 15 '19 at 08:49
  • @AlexHowansky I did a var dump and get the following: Hard Coded array: array(2) { [0]=> string(69) "Dodge>2002>Ram 3500>5.9 359cid L6 DIESEL OHV>Engine>Engine Oil Cooler" . Dynamic Array: array(37) { [0]=> string(80) "Dodge>1989>D250>5.9 359cid L6 DIESEL OHV>Engine>Engine Oil Cooler" . It seems I am getting the same result, but not the same action.. I'm still boggled lol. – Ivan D. Popov Dec 15 '19 at 17:40

0 Answers0