如何从生成的数字列表中删除最后一个管道?
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 6);
foreach ($days as $day) {
echo strtoupper($day->format('d')+543);
echo "|";
}
|
之前$s = '';
foreach ($days as $day) {
if ($s) $s .= '|';
$s .= strtoupper($day->format('d')+543);
}
echo $s;
|
仅在不是最后一项时才回显$n = iterator_count($days);
foreach ($days as $i => $day) {
echo strtoupper($day->format('d')+543);
if (($i+1) != $n) echo '|';
}
$s = array();
foreach ($days as $day) {
$s[] = strtoupper($day->format('d')+543);
}
echo implode('|', $s);
|
(或rtrim
它)$s = '';
foreach ($days as $day) {
$s .= strtoupper($day->format('d')+543) . '|';
}
echo substr($s, 0, -1);
# echo rtrim($s, '|');
在循环中收集输出,并在|
之前而不是之后添加。
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 6);
$echo = '';
foreach ($days as $day) {
if ($echo!='') $echo.='|';
$echo.=strtoupper($day->format('d')+543);
}
echo $echo;
570|571|572|573|544|545|546
在编写代码时,您不能这样做,因为:
实现您想要的结果的一种非常简单的方法是
echo implode('|', array_map(function($d) { return $d->format('d')+543; },
iterator_to_array($days)));
这通过将迭代$days
转换为数组,array_map
使用标准格式化结果并将它们粘合在一起来工作implode
。
剪切最后一个字符:
echo substr($str,0,-1);
例子
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 6);
foreach ($days as $day) {
$str .= strtoupper($day->format('d')+543);
$str .= "|";
}
echo substr($str,0,-1);
试试喜欢
$cnt = count($days);
$i = 0;
foreach ($days as $day) {
echo strtoupper($day->format('d')+543);
if($i++ < $cnt)
echo "|";
}