Php 使用;至;而不是打印数组中的每个数字

Php 使用;至;而不是打印数组中的每个数字,php,arrays,algorithm,Php,Arrays,Algorithm,有没有一种简单的方法来计算可以在范围内的数字,并用“到”来代替连续的序列 例如,如果您有以下一系列数字: $properties_no = array("1021-5152","1021-5153","1021-5154","1021-5156","1021-5157","1021-5158","1021-5159","1021-5161"

有没有一种简单的方法来计算可以在范围内的数字,并用“到”来代替连续的序列

例如,如果您有以下一系列数字:

$properties_no = array("1021-5152","1021-5153","1021-5154","1021-5156","1021-5157","1021-5158","1021-5159","1021-5161","1021-5162","1021-5163");
它将输出:

1021-5152 to 1021-5154;
1021-5156 to 1021-5159;
1021-5161 to 1021-5163

我假设您已经按照您在问题中提到的顺序获得了正确的范围

$properties_no = array("1021-5152","1021-5153","1021-5154","1021-5156","1021-5157","1021-5158","1021-5159","1021-5161","1021-5162","1021-5163");
for($i = 0; $i < count($properties_no); $i++) {
    $next = $properties_no[$i+1] ?? null;
    echo $properties_no[$i] . $next ? ("to" . $properties_no[$next]) : "\n"; 
}
$properties_no=array(“1021-5152”、“1021-5153”、“1021-5154”、“1021-5156”、“1021-5157”、“1021-5158”、“1021-5159”、“1021-5161”、“1021-5162”、“1021-5163”);
对于($i=0;$i

希望这能对你有所帮助!:)

为了给自己一些灵活性,我将定义一个简单的
Range
类来保存范围,然后创建一个函数来构建它们的列表

以下是您的
范围
定义:

final class Range
{
  private string $from;
  private string $to;

  public function __construct(string $from, string $to)
  {
    $this->from = $from;
    $this->to = $to;
  }

  public function __toString(): string
  {
    return $this->from === $this->to ? $this->from : "{$this->from} to {$this->to}";
  }
}
下面是函数:

/**
 * @param string[] $values
 * @return Range[]
 */
function computeRanges(array $values): array
{
  if (count($values) === 0) {
    return [];
  }
  $ranges = [];
  $first = $previous = $values[0];
  $previousIntValue = (int)str_replace('-', '', $first);
  foreach (array_slice($values, 1) as $value) {
    $intValue = (int)str_replace('-', '', $value);
    if ($intValue > $previousIntValue + 1) {
      $ranges[] = new Range($first, $previous);
      $first = $value;
    }
    $previous = $value;
    $previousIntValue = $intValue;
  }
  $ranges[] = new Range($first, $previous);

  return $ranges;
}
要打印所有范围(每行一个):


演示:

值得注意的是,它们是字符串,而不是数字,这会使事情变得复杂,因为您正在尝试解释和匹配连续的模式值。前缀是否总是
1021-
?如果只得到一个值,而没有前后连续的值,会发生什么情况?@fubar 1021-5152至1021-5154;1021-5156; 1021-5158至1021-5159@fubar前缀并不总是1021。它们总是采用
xxxx-yyyy
格式吗?如果末尾有值
1022-1564
echo implode(PHP_EOL, computeRanges($properties_no));