vote up 0 vote down star

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.

flag
2  
Can you clarify your question slightly? I am not really sure what you are trying to do here. thx. – Meep3D Dec 3 at 22:38
What I want is to push them into the other array but not in the same order as array1, but instead, push the first element as pat1, second element as pat2, and 3 more elements as pat3. This means that the "pattern" of 1,1,3 will be repeated for every 5 elements until all elements on array1 are gone. hope this clears it up – Josh Darrow Dec 3 at 22:54

1 Answer

vote up 0 vote down check

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";
}
link|flag

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.