如何使用PHP对范围内的数字进行分组 [英] How to group numbers in ranges using PHP
本文介绍了如何使用PHP对范围内的数字进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在数组中具有以下数字序列:
Let's say that I have the following sequence of numbers in an array:
$numbers = array(1,3,2,23,24,25,26, 8)
如何在范围内打印它们,例如:
How can I print them in ranges, for instance:
数字是1-3、23-26、8.
The numbers are 1-3, 23-26, 8.
推荐答案
这是一个简单的版本,创建包含范围的groups
Here's a simple version, creating groups
containing your ranges
<?php
$numbers = array(1,3,2,23,24,25,26,8);
sort($numbers);
$groups = array();
for($i = 0; $i < count($numbers); $i++)
{
if($i > 0 && ($numbers[$i - 1] == $numbers[$i] - 1))
array_push($groups[count($groups) - 1], $numbers[$i]);
else // First value or no match, create a new group
array_push($groups, array($numbers[$i]));
}
foreach($groups as $group)
{
if(count($group) == 1) // Single value
echo $group[0] . "\n";
else // Range of values, minimum in [0], maximum in [count($group) - 1]
echo $group[0] . " - " . $group[count($group) - 1] . "\n";
}
输出为
1 - 3
8
23 - 26
现在,如果范围的顺序很重要,就像您在问题中所描述的那样,您仍然可以对组进行排序...据我所知,您希望范围首先是单个值,然后是单个值?这可以通过添加
Now, if the order of your ranges is important, like you described in your question, you can still sort your groups... from what I can see, you want the ranges first followed by the single values? This can be done by adding
function groupRanges($a, $b)
{
if(count($a) == 1)
if(count($b) == 1)
return 0; // equal
else
return 1; // so $b is considered less than
if(count($b) == 1)
return -1; // so $a is considered less than
return 0; // both are ranges, keep them there... could be adjusted to compare the size of each range
}
usort($groups, "groupRanges");
就在foreach
之前,输出变为:
1 - 3
23 - 26
8
这篇关于如何使用PHP对范围内的数字进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文