简体   繁体   English

如何在除最后一项以外的数组数据之间插入逗号?

[英]How to insert commas between data from array except for last entry?

I'm trying to get my output to be so that commas are between all the output items except for the last one. 我正在尝试使输出为逗号,以便在除最后一项以外的所有输出项之间。 What do I need to do? 我需要做什么?

echo "The following months have 31 days: ";

for ($count=0; $count <= (count($daysInMonth) - 1); $count++) {
  if ($daysInMonth[$count] == 31){
    echo "$months[$count]" . ", ";
  }

}

You could try this. 你可以试试看。 Unless you want to manually construct the comma separated string you can use the implode function of php. 除非要手动构造用逗号分隔的字符串,否则可以使用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);

So here I am storing the values in another array and then writing it as a comma separated string. 所以在这里,我将值存储在另一个数组中,然后将其编写为逗号分隔的字符串。

You can do this: 你可以这样做:

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]";
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM