我需要通过递归来简化这个方法,以消除重复的业务逻辑,但我不知道如何做到这一点:
public function compute()
{
$ret = array();
foreach ($this->_items as $item) {
$ret[] = array($item);
}
foreach ($this->_items as $item) {
foreach ($this->_items as $item2) {
$tmp = array($item, $item2);
if (count($tmp) === count(array_unique($tmp))) {
$ret[] = $tmp;
}
}
}
foreach ($this->_items as $item) {
foreach ($this->_items as $item2) {
foreach ($this->_items as $item3) {
$tmp = array($item, $item2, $item3);
if (count($tmp) === count(array_unique($tmp))) {
$ret[] = $tmp;
}
}
}
}
return $ret;
}
编辑:
此方法应该返回数组元素的所有组合,因此如果您有如下数组:
[a, b, c]
它将返回:
[
[a],
[b],
[c],
[a, b],
[a, c],
[b, a],
[b, c],
[a, b, c],
[a, c, b],
[b, a, c],
[b, c, a],
[c, a, b],
[c, b, a]
]
最佳答案
对于您的计算,不需要递归来简化您在此处所说的业务逻辑。至少一开始不是。将重复的代码移动到它自己的函数中然后进行处理就足够了。
我还建议将此作为第一步,因为您在这里的执行顺序:
public function compute()
{
$ret = array();
foreach ($this->_items as $item) {
$ret[] = array($item);
}
$each = function(array $tmp) use (&$ret) {
if (count($tmp) === count(array_unique($tmp))) {
$ret[] = $tmp;
}
}
foreach ($this->_items as $item) {
foreach ($this->_items as $item2) {
$each(array($item, $item2));
}
}
foreach ($this->_items as $item) {
foreach ($this->_items as $item2) {
foreach ($this->_items as $item3) {
$each(array($item, $item2, $item3));
}
}
}
return $ret;
}
关于php - 用递归简化这个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12893061/