将一维数组输出到类别和子类别 html-lists

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

我有一个问题,我找不到解决它的方法。这是我的 PHP 数组,我想将其输出到按大陆->国家->地区->城市分组的 HTML 中。

这是数组:

(
[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
    (
        .....

我想在我的 HTML 中输出这个数组,格式为:

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

问题是我只想显示所有大洲一次,在大洲下每个国家只显示一次,在国家/地区下显示该数组中所有城市的列表。我尝试了很多解决方案,但其中 none 确实对我有用。感谢您的回答。

首先,我会将数组转换为更易于遍历的数组,这将为您提供更好的结构 "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];
}

然后你可以通过使用递归轻松遍历它,例如:

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