首页 > 解决方案 > 重复并合并 PHP 数组

问题描述

有了array_fill,我想重复和合并数组。

例如,当我执行时:

$array = array_fill(0, 2, array_merge(
   ['hello'],
   ['by']
));

var_dump($array);

我有这个结果:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(2) "by"
  }
  [1]=>
  array(2) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(2) "by"
  }
}

但我想要这个结果:

array(4) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(2) "by"
    [2]=>
    string(5) "hello"
    [3]=>
    string(2) "by"
}

标签: phparrays

解决方案


有很多方法可以做到这一点,但这是一个很好的机会来展示如何使用各种 PHP 迭代器来做到这一点,包括ArrayIterator,InfiniteIteratorLimitIterator; 例如:

// create an ArrayIterator with the values you want to cycle
$values = new ArrayIterator(['hello', 'by']);
// wrap it in an InfiniteIterator to cycle over the values
$cycle  = new InfiniteIterator($values);
// wrap that in a LimitIterator defining a max of four iterations
$limit  = new LimitIterator($cycle,0, 4);


// then you can simply foreach over the values 
$array = [];

foreach ($limit as $value) {
  $array[] = $value;
}

var_dump($array);

产量:

array(4) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(2) "by"
  [2]=>
  string(5) "hello"
  [3]=>
  string(2) "by"
}

希望这可以帮助 :)


推荐阅读