Search code examples
phparrayshtml-listssub-array

Output one-dimensional array into categorie and subcategorie html-lists


I have a problem and I can't find a way to solve it. This is my PHP array and I want to output it in HTML grouped by Continent->Country->Region->City.

Here is the array:

(
[0] => Array
    (
        [0] => Europe
        [1] => Spain
        [2] => Galicia
        [3] => Santiago de Compostela
    )

[1] => Array
    (
        [0] => Europe
        [1] => Spain
        [2] => Galicia
        [3] => Ferrol
    )

[2] => Array
    (
        [0] => Europe
        [1] => Spain
        [2] => Galicia
        [3] => Lugo
    )

[3] => Array
    (
        [0] => Europe
        [1] => Spain
        [2] => Andalucía
        [3] => Seville
    )

[4] => Array
    (
        [0] => South America
        [1] => Brazil
        [2] => North Region
        [3] => Manaus
    )

 [5] => Array
    (
        [0] => South America
        [1] => Brazil
        [2] => Northeast Region
        [3] => Salvador
    )

[6] => Array
    (
        .....

I would like to output this array in my HTML formatted as:

<ul> Europe
 <li> Spain
   <ul> Galicia
     <li> Santiago de Compostela </li>
     <li> Ferrol </li>
     <li> Lugo </li>
   </ul>
   <ul> Andalucía
     <li> Seville </li>
     <li> ... </li>
   </ul>
 </li>
 <li> ... </li>

<ul> South America
 <li> Brazil
   <ul> North Region
     <li> Manaus </li<
     <li> ... </li>
   </ul>
 </li>
 <li> Bolivia </li>
   <ul> ... <li> ... </li> </ul>
</ul>

<ul> ... </ul>
...

The problem is that i would like to display all continents only once, under continents every country only once and under country a list of all cities in that array. I've tried many solutions but none of them really worked for me. Thanks for your answers.


Solution

  • First I would convert the array to something more traversable, this gives you better structure "Continent => all countries in continent => all regions in country => all cities in region".

    $newArr = [];
    foreach ($yourArray as $firstLevel => $secondLevel) {
        $newArr[$secondLevel[0]][$secondLevel[1]][$secondLevel[2]][] = $secondLevel[3];
    }
    

    Then you can easily traverse trough it by using recursion for example:

    function printCategories($categories) {
       echo "<ul>";
       foreach ($categories as $categoryName => $category) {      
           echo "<li>";
           echo is_string($categoryName) ? $categoryName : "";
           if (is_array($category)) {
               printCategories($category);
           } else {
               echo $category;
           }
           echo "</li>"; 
       }
       echo "</ul>";
    }
    
    printCategories($newArr);