Marcus
Marcus

Reputation: 4480

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

Upvotes: 0

Views: 1073

Answers (2)

Matthew
Matthew

Reputation: 48284

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

Upvotes: 1

eykanal
eykanal

Reputation: 27017

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

Upvotes: 1

Related Questions