将 PHP 数组输出到无序列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14814393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:01:06  来源:igfitidea点击:

Output PHP array into unordered list

php

提问by cusejuice

New to php: I have a simple array:

php新手:我有一个简单的数组:

$people = array('Joe','Jane','Mike');

How do I output this into a list?

如何将其输出到列表中?

<ul>
 <li>Joe</li>
 <li>Jane</li>
 <li>Mike</li>
</ul>

Any help or direction would be appreciated?

任何帮助或方向将不胜感激?

回答by nickb

You can use implode()and print the list:

您可以使用implode()和打印列表:

echo '<ul>';
echo '<li>' . implode( '</li><li>', $people) . '</li>';
echo '</ul>';

Note this would print an empty <li>for an empty list - You can add a check in to make sure the array isn't empty before producing any output (which you would need for any loop so you don't print an empty <ul></ul>).

请注意,这将为<li>空列表打印一个空- 您可以添加一个签入以确保在生成任何输出之前数组不为空(任何循环都需要它,因此您不会打印空<ul></ul>)。

if( count( $people) > 0) {
    echo '<ul>';
    echo '<li>' . implode( '</li><li>', $people) . '</li>';
    echo '</ul>';
}

回答by mallix

Try:

尝试:

echo '<ul>';
foreach($people as $p){
 echo '<li>'.$p.'</li>';
}
echo '</ul>';

回答by jeroenvisser101

Try this:

尝试这个:

echo "<ul>";
foreach(people as $person){
  echo "<li>". $person ."</li>";
}
echo "</ul>";

回答by Tomá? Zato - Reinstate Monica

You need to use loop to output array data as text.

您需要使用循环将数组数据输出为文本。

There are multiple loops in PHP:

PHP 中有多个循环:

FOR

为了

For will iterate $i (can be diferent variable and different change than iteration) and will end when the condition is not true anymore.

For 将迭代 $i(可以是与迭代不同的变量和不同的变化),并在条件不再为真时结束。

$people = array('Joe','Jane','Mike');
for($i=0; $i<count($people); $i++) {  //end when $i is larger than amount of people
    echo "  <li>{$people[$i]}</li>\n";
}

FOREACH

FOREACH

Very useful for unordered arrays - this loop will give you all values in the array as variable you want:

对于无序数组非常有用 - 这个循环会给你数组中的所有值作为你想要的变量:

$people = array('Joe','Jane','Mike');
foreach($people as $human) {  //end when $i is larger than amount of people
    echo "  <li>$human</li>\n";
}

WHILE

尽管

Like FOR, loops while condition is met.

与 FOR 一样,满足条件时循环。

回答by Dawid Sajdak

<?php

echo "<ul>";

foreach(array("test", "test2", "test3") as $string)) {
    echo "<li>".$string."</li>"
}

echo "<ul>";

?>