如何在 PHP 中返回数组的排列?
我有一个函数,它接受一维数组并返回数组中元素的所有可能的排列;
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);
第一次调用该函数时,它会按预期工作,但是第二次调用它时,它还包含第一个数组中的元素。我不明白这是为什么。
感谢您的帮助。
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.
Appreciate the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您使用的是
static $permuted_array;
,所以您必须使用
using
static $permuted_array = array();
不会将其值设置为array(
)第一次迭代后,又添加了一个参数 $isNew。如果您想获取新数组的结果,请发送 true。
Because you are using
static $permuted_array;
you must use
using
static $permuted_array = array();
will not set its value toarray(
) after first iterationone more parameter is added $isNew. Send true if you want to get result for new array.
我知道这个问题已经很老了,但这里有一个替代解决方案,通过引用传递返回数组:
I know this question is old, but here's an alternative solution passing the return array by reference:
固定版本,
您可以将其用作
$perms = array_2D_permute($arr);
fixed version
you can use it as
$perms = array_2D_permute($arr);