php中n,在PHP中连接n个数组的值

您可以枚举结果集的元素,也就是说,对于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

(自然排序)集的第个元素。因为您只需要一个整数来存储当前状态,所以当您有多个/大的数组时,内存消耗不会“爆炸”。正如克里斯在他的评论中所说,你用速度(当使用较小的集合时)来交换低内存消耗。(尽管我认为-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

,A

SeekableIterator

甚至可能是

ArrayAccess

(从而将控制与递归解进行比较,

几乎

像一个

yield

在python或ruby中)

$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();

// add parameter arrays in reverse order so we can use foreach() in current()

// could use array_reverse(), but you might want to check is_array() for each element.

$this->data = array();

foreach($params as $p) {

//

array_unshift($this->data, $p);

}

$this->current = 0;

// there are |arr1|*|arr2|...*|arrN| elements in the result set

$this->limit = array_product(array_map('count', $params));

}

public function current() {

/* this works like a baseX->baseY converter (e.g. dechex() )

the only difference is that each "position" has its own number of elements/"digits"

*/

// valid() -->

$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

(顺序似乎正常;-)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值