您可以枚举结果集的元素,即对于0....(元素数)-1之间的每个整数,您可以告诉要返回哪个元素(即有一种自然顺序)。 对于给定的示例:
0 => array1[0], array2[0], array3[0]
1 => array1[0], array2[0], array3[1]
2 => array1[0], array2[1], array3[0]
7 => array1[1], array2[1], array3[1]
您只需要一个(整数)索引n和一个将索引“翻译”为(自然排序的)集合的第n个元素的函数。由于您只需要一个整数来存储当前状态,所以当您有多个/大型数组时,内存消耗不会“爆炸”。正如Chris在他的评论中所说,您在使用较小的集合时会换取速度,以降低内存消耗。(虽然我认为-通过php的实现方式-这也是一个合理快速的解决方案。)
$array1 = array('dog', 'cat');
$array2 = array('food', 'tooth');
$array3 = array('car', 'bike');
function foo( $key ) {
$params = func_get_args();
$rv = array();
$key = array_shift($params);
$i=count($params);
while( 0 < $i-- ) {
array_unshift($rv, $params[$i][ $key % count($params[$i]) ]);
$key = (int)($key / count($params[$i]));
}
return $rv;
}
for($i=0; $i<8; $i++) {
$a = foo($i, $array1, $array2, $array3);
echo join(', ', $a), "\n";
}
您可以使用这个方法来实现例如
Iterator,
SeekableIterator 或者甚至是
ArrayAccess(与递归解决方案相比,控制被颠倒,几乎像 Python 或 Ruby 中的
yield
)。
<?php
$array1 = array('dog', 'cat', 'mouse', 'bird');
$array2 = array('food', 'tooth', 'brush', 'paste');
$array3 = array('car', 'bike', 'plane', 'shuttlecraft');
$f = new Foo($array1, $array2, $array3);
foreach($f as $e) {
echo join(', ', $e), "\n";
}
class Foo implements Iterator {
protected $data = null;
protected $limit = null;
protected $current = null;
public function __construct( ) {
$params = func_get_args();
$this->data = array();
foreach($params as $p) {
array_unshift($this->data, $p);
}
$this->current = 0;
$this->limit = array_product(array_map('count', $params));
}
public function current() {
$rv = array();
$key = $this->current;
foreach( $this->data as $e) {
array_unshift( $rv, $e[$key % count($e)] );
$key = (int)($key/count($e));
}
return $rv;
}
public function key() { return $this->current; }
public function next() { ++$this->current; }
public function rewind () { $this->current = 0; }
public function valid () { return $this->current < $this->limit; }
}
打印
dog, food, car
dog, food, bike
dog, food, plane
dog, food, shuttlecraft
dog, tooth, car
dog, tooth, bike
[...]
bird, paste, bike
bird, paste, plane
bird, paste, shuttlecraft
(这个序列似乎没问题;-))