2009-12-03 45 views
0

我有一个数组,看起来像这样PHP在array1推模式ARRAY2

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

我想将其推入另一个数组所以数组2的输出如下:

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

我想是推动他们在以下模式:1“PAT1” 1“PAT2”和3“PAT3”,并重复这一模式,每5元。

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 
} 

这样做的好方法是什么?

任何想法将不胜感激。

+2

你能澄清你的问题稍微的迭代器?我不确定你在这里做什么。谢谢。 – Meep3D 2009-12-03 22:38:34

+0

我想是将它们推入另一阵列而不是在相同的顺序ARRAY1,而是,推动第一元件作为PAT1,第二元件作为PAT2,和3种以上的元素作为PAT3。这意味着1,1,3的“模式”将每5个元素重复一次,直到array1上的所有元素都消失为止。希望这可以清除它 – 2009-12-03 22:54:12

回答

0

时间的一些有趣的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"; 
}