Push Array value to every other Array value?



我不知道如何解释我的问题。

我有这样的数组

$foo = array{"one", "two", "three"}

,我需要将每个值压入到另一个值

需要这样的结果…

$new = array{"one two three", "one two", "one three", "two three", "one", "two", "three"}

那样的结果可能吗?

我希望有人能帮助我。

这是对您的问题的一个相当简单的尝试。

<?php
function perms($array) {
    $res = array( array() );
    foreach ($array as $val) {
        $n = count($res);
        for($i=0; $i < $n; $i++) {
            $res[] = array_merge( array($val), $res[$i] );
        }
    }
    return $res;
}
$array = array("one", "two", "three");
print_r( perms($array) );

结果可以在Ideone上找到。输出是多维形式的,但我相信您可以找出如何使其扁平化的方法。

似乎你正在寻找一个powerset,这里是一个链接到算法:http://en.wikipedia.org/wiki/Power_set

最新更新