我想在下面的代码中的最后一个$member
末尾添加一个空行,以区分每个组。我试过下面的代码
foreach($members as $key => $member)
{
$member = trim(preg_replace('/\s\s+/', ' ', $member));
$dev = " $member part of Form; <br>";
echo str_replace("<br>", "\r\n", $dev);
if($key == count($member)-0)
{
$space = "<br>";
echo str_replace("<br>", "\r\n", $space);
}
}
但它在每两行之后添加一个空格。如何只在最后一个字符串的末尾添加空格?
答案 0 :(得分:2)
foreach($members as $key => $member)
{
$member = trim(preg_replace('/\s\s+/', ' ', $member));
$dev = " $member part of Form; <br>";
echo str_replace("<br>", "\r\n", $dev);
if($key == count($members)-1) <!--- ** check this line ---->
{
$space = "<br>";
echo str_replace("<br>", "\r\n", $space);
}
}
**您已经计算了密钥($ member)的值,但实际上它将是原始数组($ members)的计数。这里$ key从零开始,它将结束前一个总数组计数。
我不知道$ members的数组结构。您可以使用以下代码
$count = count($members);
$i = 1;
foreach($members as $key => $member)
{
$member = trim(preg_replace('/\s\s+/', ' ', $member));
$dev = " $member part of Form; <br>";
echo str_replace("<br>", "\r\n", $dev);
if($i == $count)
{
$space = "<br>";
echo str_replace("<br>", "\r\n", $space);
}
$i ++;
}
答案 1 :(得分:1)
我不确定我明白你在问什么。如果要在最后一项之后添加换行符,可以在循环后执行此操作:
foreach ($members as $key => $member) {
# ...
}
echo "\r\n";
如果你在循环中需要它,你需要测试最后一个键。一种方法是操纵array's internal pointer:
# Set internal pointer of array to the last entry:
end($members)
# Get the key of that last entry:
$lastKey = key($members)
foreach ($members as $key => $member) {
# ...
if ($key === $lastKey) {
echo "\r\n";
}
# ...
}
答案 2 :(得分:1)
要在最后一个字符串&#34;的末尾添加换行符&#34;,只需在循环后回显它。但是使用常量PHP_EOL而不是&#34; \ r \ n&#34;。
将PHP_EOL连接到每个行的末尾将为您提供在浏览器和命令行中显示或多或少相同的输出。在循环之后再回显一个PHP_EOL将插入一个空白行,该行在命令行中可见,但不能从浏览器中看到。如果您在浏览器中需要一个空行(更多空格),请改用CSS。
由于您似乎已经知道如何替换<br>
标记,因此我忽略了您的部分代码。如果您确实需要替换这些标记而不是仅仅通过命令行使文本更具可读性,那么您可以轻松地执行此操作。
$ cat code/php/test.php
<?php
$members = array(0 => 'Member0', 1 => 'Member1', 2 => 'Member2', 3 => 'Member3');
foreach($members as $key => $member)
{
$member = trim(preg_replace('/\s\s+/', ' ', $member));
echo " $member part of Form; <br>".PHP_EOL;
}
echo PHP_EOL;
?>
$ php code/php/test.php
Member0 part of Form; <br>
Member1 part of Form; <br>
Member2 part of Form; <br>
Member3 part of Form; <br>
$
答案 3 :(得分:0)
$numItems = count($members);
$i = 0;
foreach($members as $key=>$member) {
if(++$i === $numItems) {
$space = "<br">;
echo str_replace("<br>", "\r\n", $space);
}
}
Find the last element of an array while using a foreach loop in PHP