根据值将数组分成几组 [英] Breaking an array into groups based on values
问题描述
我正在使用PHP,根据一组值将一个数组分解为多个数组。这些组基于介于1到5之间的值。但是这是困难的部分...
Using PHP, I'm trying to break an array up into multiple arrays based on groups of values. The groups are based on the values being between 1 and 5. But here's the hard part...
我需要遍历数组并放入第一组值在自己的数组中是1到5之间,然后在自己的数组中是下一个在1到5之间的值,依此类推。
I need to loop through the array and put the first set of values that are between 1 and 5 in their own array, then the next set of values that are between 1 and 5 in their own array, and so on.
但是每个组不会总是包含1,2,3,4,5。某些组可能是随机的。
But each group WON'T always include 1,2,3,4,5. Some groups could be random.
示例:
1,1,2,2,3,4, 5-这将是一个组
1,1,2,2,3,4,5 - this would be a group
1,2,3,4,4,4-这将是一个组
1,2,3,4,4,4 - this would be a group
1,2,3,3,5-这将是一个组
1,2,3,3,5 - this would be a group
2,2,3,3,5-这将是一个组
2,2,3,3,5 - this would be a group
所以我不能只测试特定数字。
So I can't just test for specific numbers.
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 1
[6] => 2
[7] => 3
[8] => 4
[9] => 4
[10] => 1
[11] => 1
[12] => 3
[13] => 4
[14] => 5
)
有任何想法吗?
推荐答案
我只是检查当前值是否大于先前值,如果是, ,开始一个新组。
I would just check if the current value is larger than the previous value, and if yes, begin a new group.
$groups = array();
$groupcount = 1;
foreach( $array as $key=>$value )
{
if( $key > 0 ) // there's no "previous value" for the first entry
{
if( $array[$key] < $array[$key-1] )
{
$groupcount = $groupcount + 1;
}
}
$group[groupcount][] = $value;
}
这篇关于根据值将数组分成几组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!