开发者

Breaking an array into groups based on values

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...

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 开发者_JAVA技巧1 and 5 in their own array, and so on.

But each group WON'T always include 1,2,3,4,5. Some groups could be random.

Examples:

1,1,2,2,3,4,5 - this would be a group

1,2,3,4,4,4 - this would be a group

1,2,3,3,5 - this would be a group

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
)

Any Ideas?


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


Is this what you are looking for?

$groups = array();
$cur = array();
$prev = 0;
foreach ($numbers as $number)
{
  if ($number < $prev)
  {
    $groups[] = $cur;
    $cur = array();
  }
  $cur[] = $number;
  $prev = $number;
}
if ($cur) $groups[] = $cur;

Untested. (Edit: corrected some obvious mistakes.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜