如何返回数组的排列在PHP? [英] How to return permutations of an array in PHP?
问题描述
我有取一维阵列并返回该数组中的元素的所有可能的排列的函数;
I have a function that take a one dimensional array and returns all the possible permutations of the elements within the array;
function array_2D_permute($items, $perms = array()) {
static $permuted_array = array();
if (empty($items)) {
$permuted_array[]=$perms;
#print_r($new);
#print join(' ', $perms) . "\n";
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
array_2D_permute($newitems, $newperms);
}
return $permuted_array;
}
}
$arr1=array("Architecture","Mexico","Periodicals");
$result1=array_2D_permute($arr1);
print_r($result1);
$arr2=array("Apple","Boat","Cat");
$result2=array_2D_permute($arr2);
print_r($result2);
第一次调用函数时,它按预期工作,但它被称为第二次,它也包括从第一个数组元素。我想不通这是为什么。
The first time the function is called, it works as expected, however the second time it is called, it also includes elements from the first array. I can't figure out why this is.
鸭preciate的帮助。
Appreciate the help.
推荐答案
由于您使用的是静态$ permuted_array;
您必须使用
static $permuted_array; // declare static var, if you don't want to use static property of variable, then why are you using this
$permuted_array = array(); // set its value to array()
使用
静态$ permuted_array =阵列();
不会将其值设置为阵列(
)第一个循环之后
using static $permuted_array = array();
will not set its value to array(
) after first iteration
function array_2D_permute($items, $perms = array(), $isNew = false) {
static $permuted_array = array();
if($isNew)
$permuted_array = array();
if (empty($items)) {
$permuted_array[]=$perms;
#print_r($new);
#print join(' ', $perms) . "\n";
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
array_2D_permute($newitems, $newperms);
}
return $permuted_array;
}
}
$arr1=array("Architecture","Mexico","Periodicals");
$result1=array_2D_permute($arr1, array(), true); //
print_r($result1);
$arr2=array("Apple","Boat","Cat");
$result2=array_2D_permute($arr2, array(), true); ///
print_r($result2);
一个参数被添加$是否新款。如果你想获得的结果为新的阵列发送正确的。
one more parameter is added $isNew. Send true if you want to get result for new array.
这篇关于如何返回数组的排列在PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!