我试图将输出设置为使逗号位于除最后一个之外的所有输出项之间。我需要做什么?
echo "The following months have 31 days: ";
for ($count=0; $count <= (count($daysInMonth) - 1); $count++) {
if ($daysInMonth[$count] == 31){
echo "$months[$count]" . ", ";
}
}
答案 0 :(得分:2)
你可以试试这个。
除非您想手动构造逗号分隔字符串,否则可以使用php的implode
函数。
<?php
$longMonths = array();
$daysInMonth = [31,30,31];
$months = ['Jan','Sep','Dec'];
for ($count=0; $count <= (count($daysInMonth) - 1); $count++) {
if ($daysInMonth[$count] == 31){
$longMonths[] = $months[$count];
}
}
echo implode(', ', $longMonths);
所以这里我将值存储在另一个数组中,然后将其写为逗号分隔的字符串。
答案 1 :(得分:0)
你可以这样做:
echo "The following months have 31 days: ";
for ($count=0; $count <= (count($daysInMonth) - 1); $count++) {
if ($daysInMonth[$count] == 31 && $months[$count] != "December"){
echo "$months[$count]" . ", ";
}
if ($daysInMonth[$count] == 31 && $months[$count] == "December") {
echo "$months[$count]";
}
}