views:

51

answers:

1

I have an array that looks something like this

array(7) {
  [0]=> "hello,pat1"
  [1]=> "hello,pat1"
  [2]=> "test,pat2"
  [3]=> "test,pat2"
  [4]=> "foo,pat3"
  [5]=> "foo,pat3"
  [6]=> "foo,pat3"
  ....
}

I would like to push it into another array so the output of the array2 is as follow:

array(7) {
  [0]=> "hello,pat1"
  [1]=> "test,pat2"
  [2]=> "foo,pat3"
  [3]=> "foo,pat3"
  [4]=> "foo,pat3"
  [5]=> "hello,pat1"
  [6]=> "test,pat2"
  .....
}

What I want is to push them in the following pattern: 1 "pat1" 1 "pat2" and 3 "pat3", and repeat this pattern every 5 elements.

while ( !empty( $array1 ) )
  $a = explode(",",$array1[$i]);
  if($a[1]=='pat1' &&)
     push && unset
  elseif($a[1]=='pat2' &&)
     push && unset
  elseif($a[1]=='pat3' and < 5)
     push && unset and reset pattern counter
}

What would be a good way of doing this?

Any idea will be appreciate it.

A: 

Time for some fun with the iterators of the Standard PHP Library :-)

<?php
$array1 = array (
  "hello1,pat1", "hello2,pat1", "hello3,pat1",
  "test1,pat2", "test2,pat2",
  "foo1,pat3", "foo2,pat3", "foo3,pat3",
  "foo4,pat3", "foo5,pat3", "foo6,pat3"
);

// "group by" patN
$foo = array();
foreach($array1 as $a) {
  // feel free to complain about the @ here ...to somebody else
  @$foo[ strrchr($a, ',') ][] = $a;
}
// split pat3 into chunks of 3
$foo[',pat3'] = array_chunk($foo[',pat3'], 3);

// add all "groups" to a MultipleIterator
$mi = new MultipleIterator(MultipleIterator::MIT_NEED_ANY);
foreach($foo as $x) {
  $mi->attachIterator( new ArrayIterator($x) );
}

// each call to $mi->current() will return an array
// with the current items of all registered iterators
foreach ($mi as $x) {
  // "flatten" the nested arrays
  foreach( new RecursiveIteratorIterator(new RecursiveArrayIterator($x)) as $e) {  
    echo $e, "\n";
  }
  echo "----\n";
}
VolkerK