如何从生成的数字列表中删除最后一个管道?
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 6);
foreach ($days as $day) {
echo strtoupper($day->format('d')+543);
echo "|";
}
答案 0 :(得分:5)
|
$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, '|');
答案 1 :(得分:3)
在循环中收集输出,并在之前而不是之后添加|
。
$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
答案 2 :(得分:3)
由于编写代码,因此无法执行此操作:
实现所需结果的一种非常简单的方法是
echo implode('|', array_map(function($d) { return $d->format('d')+543; },
iterator_to_array($days)));
这可以通过将$days
的迭代转换为数组,使用array_map
格式化结果并使用标准implode
将它们粘合在一起来实现。
答案 3 :(得分:0)
剪切最后一个字符:
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);
答案 4 :(得分:0)
尝试
$cnt = count($days);
$i = 0;
foreach ($days as $day) {
echo strtoupper($day->format('d')+543);
if($i++ < $cnt)
echo "|";
}
答案 5 :(得分:-1)