php将模式从array1推送到array2

时间:2009-12-03 22:15:18

标签: php arrays while-loop

我有一个看起来像这样的数组

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

我想将它推入另一个数组,因此array2的输出如下:

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 个答案:

答案 0 :(得分: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";
}

答案 1 :(得分:0)

我想我将以各自的增量设置各自的计数器。由于php会将浮点键转换为整数,因此您可以使用,pat3而不是.33来递增1项。然后,要将结果展平,只需将splat运算符与array_merge()一起使用。

代码:(Demo

$array = [
    "hello1,pat1",
    "hello2,pat1",
    "test3,pat2",
    "test4,pat2",
    "foo5,pat3",
    "foo6,pat3",
    "foo7,pat3",
];

$counters = [',pat1' => 0, ',pat2' => 0, ',pat3' => 0];
foreach ($array as $value) {
    $end = strrchr($value, ',');
    $groups[$counters[$end]][] = $value;
    $counters[$end] += ($end === ',pat3' ? .33 : 1);
}

var_export(array_merge(...$groups));

输出:

array (
  0 => 'hello1,pat1',
  1 => 'test3,pat2',
  2 => 'foo5,pat3',
  3 => 'foo6,pat3',
  4 => 'foo7,pat3',
  5 => 'hello2,pat1',
  6 => 'test4,pat2',
)