Firestarter Firestarter - 1 month ago 5
PHP Question

Nested array into menu, but with urls generation

Pleaser help to create menu with nested urls.

I have a mulidimentual array, like this:

["Увлажнение"]=>
array(0) {
}
["Туалетная вода"]=>
array(0) {
}
["Духи и парфюмерная вода"]=>
array(0) {
}
["Мужские аксессуары"]=>
array(13) {
["Часы"]=>
array(1) {
["Часы"]=>
array(0) {
}
}
["Сумки и чехлы"]=>
array(8) {
["Спортивные сумки"]=>
array(0) {
}
["Сумки"]=>
array(0) {
}
["Рюкзаки"]=>
array(0) {
}


I have a function that create HTML Menu from this array:

function makeList($array) {

//Base case: an empty array produces no list
if (empty($array)) return '';

//Recursive Step: make a list with child lists
$output = '<ul>';

foreach ($array as $key => $subArray) {

$url = URLify::filter ($key);

$output .= '<li><a href="'.$url.'">' . $key .'</a>'. makeList($subArray) . '</li>';

}

$output .= '</ul>';

return $output;

};


That generame manu like:

  • Увлажнение
  • Туалетная вода
  • Духи и парфюмерная вода
  • Мужские аксессуары
    • Часы
  • Сумки и чехлы
    • Спортивные сумки
    • Сумки


Every menu urls like:


  • uvlazhnenie

  • tualetnaya-voda

  • duhi-i-parfyumernaya-voda

  • muzhskie-aksessuary

  • chasy



But i need urls like:
muzhskie-aksessuary/chasy

With nested (with delemiter) urls.

Please help me. Thanks.

Answer

You can use a second argument for your function for this:

function makeList($array, $url = '') {
    //Base case: an empty array produces no list
    if (empty($array)) return '';
    //Recursive Step: make a list with child lists
    $output = '<ul>';
    foreach ($array as $key => $subArray) {
        $url2 = $url . ($url == '' ? '' : '/') . URLify::filter ($key);
        $output .= '<li><a href="'.$url2.'">' . $key .'</a>'. makeList($subArray, $url2) . '</li>';
    }
    $output .= '</ul>';
    return $output;
}