我有一个$数组,我想按如下方式组合每个二级元素:
$array['A'] = array('a','b','c');
$array['B'] = array('d','e','f');
$array['C'] = array('g','h','i');
function combine($array)
{
$result = array();
foreach($array['A'] as $a)
{
foreach($array['B'] as $b)
{
foreach($array['C'] as $c)
{
$result[] = array($a,$b,$c);
}
}
}
return $result;
}
只有当count($array)为3时,combine()才能正常显示正确的结果。如果我添加更多的$array元素,例如,$array['D'] = array('j','k','l'),那么它就不能正常工作了。
如何解决这个问题?
我想我应该用递归函数。但是我对这类编程没有任何经验。
你能帮我吗?
啊,不错的问题。实际上,我不得不在很多场合重新实现这个。这应该对你有用:
class Counter {
private $bases;
private $currNum;
private $increment;
private $maxVal;
public function __construct($bases) {
$this->bases = $bases;
$this->maxVal = 1;
$this->currNum = array();
foreach ($bases as $base) {
$this->maxVal *= $base;
$this->currNum[] = 0;
}
$this->increment = 0;
}
public function increment() {
++$this->increment;
for ($i = count($this->currNum) - 1; $i > -1; --$i) {
$val = $this->currNum[$i] + 1;
if ($val >= $this->bases[$i]) {
$this->currNum[$i] = 0;
} else {
$this->currNum[$i] = $val;
return;
}
}
}
// TODO handle overflows
public function hasNext() {
return $this->increment < $this->maxVal;
}
public function getNum() {
return $this->currNum;
}
public function getIncrement() {
return $this->increment;
}
}
// your sample arrays
$arrays = array(
array('a', 'b', 'c'),
array('d', 'e', 'f'),
array('g', 'h', 'i')
);
// parameter to counter changes based on how many arrays you have
// if you have 4 arrays of len 4, it'll be $counter = new Counter(array(4,4,4,4));
// it'll work with arrays of varying lengths as well.
// so if you have 1 array of len 2, another of len 3 and a third of len 4:
// $counter = new Counter(array(2,3,4));
$counter = new Counter(array(3,3,3));
$result = array();
while ($counter->hasNext()) {
$indexes = $counter->getNum();
//print_r($indexes);
$result[] = array();
foreach ($indexes as $arr => $index) {
$result[count($result) - 1][] = $arrays[$arr][$index];
}
$counter->increment();
}
print_r($result);
我改变$阵列[A]$阵列[B]被索引为数组美元[0]$array[1]等,使其更易于使用。
counter->getNum()
返回数组索引。你可以选择是否选择那个元素
问题是您的函数要求其参数是如下结构的数组:
Array
(
[A] => Array()
[B] => Array()
[C] => Array()
)
我想添加另一个键'D'实际上并没有破坏函数,你只是没有得到你想要的结果。
您可以使用array_map(null, $array['A'], $array['B'], $array['C'], $array['D'])
。
array_map可以构造一个数组的数组,通过使用null作为回调。