如何在 HTML 中迭代 PHP 数组

我试图在内部迭代以下 PHP 数组和 HTML 模板:


$sub_menu = array(

    array(

        'titulo' => 'Ropa',

        'url' => '/ropa.html

    '),

    array(

        'titulo' =>'Electronica',

        'url' => '/electronica.html'

    ),

    array(

        'titulo' => 'Higiene',

        'url' =>'/higiene.html'

    ),

    array(

        'titulo' => 'Alimentos',

        'url' => '/alimentos.html'

    ),

    array(

        'titulo' => 'Otros',

        'url' => '/otros.html'

    )

);

到目前为止还不是很幸运。我想要做的是将其显示为导航标签内的列表。


你能帮我一下吗?


所以我试过了


<?php 

echo '<ul>'; 

foreach ($sub_menu as $parent) { 

    if (is_array($parent)) { 

        echo '<ul>'; 

        foreach ($parent as $children => $key) { 

            echo '<li><a href="#">' . $children . '</a>'; 

        } 

        echo '</ul>'; 

    } 

    echo '</li>'; 

echo '</ul>'; 

?>


呼唤远方
浏览 140回答 3
3回答

慕勒3428872

我认为您使它比所需的输入数组复杂一点$sub_menu = array(&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; 'titulo' => 'Ropa',&nbsp; &nbsp; &nbsp; &nbsp; 'url' => '/ropa.html'),&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; 'titulo' =>'Electronica',&nbsp; &nbsp; &nbsp; &nbsp; 'url' => '/electronica.html'&nbsp; &nbsp; ),&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; 'titulo' => 'Higiene',&nbsp; &nbsp; &nbsp; &nbsp; 'url' =>'/higiene.html'&nbsp; &nbsp; ),&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; 'titulo' => 'Alimentos',&nbsp; &nbsp; &nbsp; &nbsp; 'url' => '/alimentos.html'&nbsp; &nbsp; ),&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; 'titulo' => 'Otros',&nbsp; &nbsp; &nbsp; &nbsp; 'url' => '/otros.html'&nbsp; &nbsp; ));echo '<ul>'.PHP_EOL;&nbsp;foreach ($sub_menu as $parent) {&nbsp;&nbsp; &nbsp; echo '<li><a href="' . $parent['url'] . '">' . $parent['titulo'] . '</a></li>'.PHP_EOL;&nbsp;}&nbsp;echo '</ul>'.PHP_EOL;&nbsp;结果<ul><li><a href="/ropa.html">Ropa</a></li><li><a href="/electronica.html">Electronica</a></li><li><a href="/higiene.html">Higiene</a></li><li><a href="/alimentos.html">Alimentos</a></li><li><a href="/otros.html">Otros</a></li></ul>

大话西游666

使用基本foreach()循环来呈现您的“导航栏”...编辑 HTML 以满足您的特定需求:foreach&nbsp;($sub_menu&nbsp;as&nbsp;$key&nbsp;=>&nbsp;$value)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;"<li><a&nbsp;href='"&nbsp;.&nbsp;$value['url']&nbsp;.&nbsp;"'>"&nbsp;.&nbsp;$value['titulo']&nbsp;.&nbsp;"</a></li>"; }

梦里花落0921

你在错误的地方有 echo ul 试试下面的代码<?php&nbsp; &nbsp;echo "<ul>";foreach ($sub_menu as $parent) {&nbsp;&nbsp; &nbsp; if (is_array($parent)) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; echo '<li><ul>';&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; foreach ($parent as $children => $key) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo '<li><a href="#">' . $children . '</a>';&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; echo '</ul></li>';&nbsp;&nbsp; &nbsp; }else {&nbsp; &nbsp; &nbsp; &nbsp; echo '<li><a href="#">' . $parent . '</a>';&nbsp;&nbsp; &nbsp; }&nbsp;}&nbsp;&nbsp;echo "</ul>";?>
打开App,查看更多内容
随时随地看视频慕课网APP