Forum Moderators: coopster

Message Too Old, No Replies

Array Function Needed - Find count of "Groupings"

Find a count of "groupings" of non-zero/null values in array

         

HappyJupiter

9:11 pm on Aug 22, 2010 (gmt 0)

10+ Year Member



Hello all!

I'd like to find a nice neat way of checking if an array has one "grouping" of values or more than one "grouping" of values (or no groupings at all). I need help building a function to do this. (I could do this with looping and lots of variables, but I'm hoping that I'm just forgetting about some really handy php array functions :)

examples:

#1
$my_array=array(0,0,1,1,1,0,0,0);
$result=multiple($my_array);

$result would equal 1 since there is one group of values together without gaps (zero/null values)

#2
array(0,0,1,1,1,0,1,0);
$result=multiple($my_array);

$result would equal 2 since there is two groups of values together without gaps (zero/null values)


#3
array(0,0,0,0,0,0,0,0);
$result=multiple($my_array);

$result would equal 0 since there are no groups of values together without gaps (zero/null values)


Any help would be wonderful! Thanks in advance!

alias

2:34 pm on Aug 23, 2010 (gmt 0)

10+ Year Member



Can't recall a filter function that would help you in this case, and can't think of a short sorting function that would be useful in here.

But even the raw script is rather simple in my non-dev eyes:

<?php
$previous = false;
$grouping = false;
$groups = 0;
$myArray = array(1,1,0,1,1,0,1,1,0,1,1,0);
for($i=0,$l=count($myArray);$i<$l;$i++){
if($myArray[$i] && $myArray[$i]===$previous){
$grouping = true;
} else {
if($grouping){
$groups++;
}
$grouping = false;
}
$previous = $myArray[$i];
}
if($grouping){
$groups++;
}
print_r($groups);
?>


That is a bit dirty but it works -- I suppose that is something you would've build yourself.

lostdreamer

7:26 am on Aug 24, 2010 (gmt 0)

10+ Year Member



without looping through the entire array (probably faster on big ones)

function multiple($arr) {
$str = implode($arr, " ");
$str = str_replace(" ", " 0 ", $str);// this will fill NULLs with 0's
$str = str_replace(" ", "", $str);// get rid of spaces
// adding a few 0's around it so we also catch beginning and ending 1's
$tmp = preg_split("|(1+)|U", "0".$str."0", null, PREG_SPLIT_NO_EMPTY);
return COUNT($tmp)-1;
}