如何在php中用一个变量列出所有条目[duplicate]

jhdbpxl9  于 2022-12-28  发布在  PHP
关注(0)|答案(1)|浏览(110)
    • 此问题在此处已有答案**:

How to loop through an array and print each item into an tag using PHP?(6个答案)
PHP - For loop only returns last variable in array(2个答案)
php for and foreach loop only storing last value(2个答案)
Why I get only the last entrie of array with foreach loop [closed](1个答案)
Foreach returns only the last item(1个答案)
15小时前关门了。
我正在创建Joomla 4网站由动物园(CCK)供电。在自定义模板中,我想得到一个突出显示的主题在一篇文章中的列表。突出显示多达四个。但php代码只获取第一个突出显示。以及我想设置一个变量,列出所有三个突出显示。
我试过下面的代码:

<?php 
// get this list of all highlights of the article

foreach ($limeLights as $limeLight) {
     $highlight = '<li class="hlli">'.$limeLight['value'].'</li>';
}

// set variable for highlights element

$highlights     = '<div class="hlit">'
                  .'<h2 class="hliz">Highlights</h2><ul class="hlul">'
                  .''.$highlight.''
                  .'</ul></div>';
?>
<?php echo $highlights; ?>

预期的html输出:

<div class="hlit">
<h2 class="hliz">Highlights</h2>
<ul class="hlul">
<li class="hlli">01. This is the first item from the list</li>
<li class="hlli">02. This is the second item from the list</li>
<li class="hlli">03. This is the third item from the list</li>
</ul>
</div>

但是我得到的html输出:

<div class="hlit">
<h2 class="hliz">Highlights</h2>
<ul class="hlul">
<li class="hlli">01. This is the first item from the list</li>
</ul>
</div>
nr9pn0ug

nr9pn0ug1#

您可以稍微重新排列代码,将其作为一个字符串来完成:

$highlights      = '<div class="hlit">'
                  .'<h2 class="hliz">Highlights</h2><ul class="hlul">';

foreach ($limeLights as $limeLight) {
    $highlights .= '<li class="hlli">'.$limeLight['value'].'</li>';
}

$highlights     .= .'</ul></div>';

相关问题