If I understand the logic that you are trying to apply, SplQueue provides all the possibilities for a thorough and accurate solution to your problem.
I wrote this and it tests me perfectly based on the use case you use.
// your data array $array = array( array("filename"=>"image0.jpg","orientation"=>"V"), array("filename"=>"image1.jpg","orientation"=>"H"), array("filename"=>"image2.jpg","orientation"=>"H"), array("filename"=>"image3.jpg","orientation"=>"H"), array("filename"=>"image4.jpg","orientation"=>"H")); function queue($array) { // grab a new SqlQueue object -- http://php.net/manual/en/class.splqueue.php $q = new SplQueue; foreach($array as $key=>$val) { // if this is the first iteration or the queue object was emptied out if ($q->isEmpty()) { $q->enqueue($val); } else { if ($val['orientation'] == $array[$key--]['orientation']) { $q->enqueue($val); if (($q->count() % 4) == 0) { return $q; } } else { // Dequeue the whole group on interrupt while ($q->valid()) { $q->dequeue(); } // ... and start filling the queue, the mismatch as the new pattern $q->enqueue($val); } } } } $q = queue($array); echo $q->count();
The properties of the enqueued() sets property are private, so you have to make them visible in your class.
If you are using PHP 5.4+, you can replace this index call with a reduced array by dereferencing an array of functions, for example:
if ($val['orientation'] == prev($array[$key])['orientation'] {
Everything else is pretty standard. A module test returns a queue object as soon as it receives 4 matches in a row, since SplQueue objects provide a sequence of indexed FIFOs and cannot be unchanged. Finally, if the interrupt matches before the queue has 4 matches in the row, the Split iterators empties the queue to begin with - starting with the mismatch (first new pattern.)
This should cover everything ...
Hth :)
source share