开发者

PHP Clean Up Permutated Array

开发者 https://www.devze.com 2022-12-13 21:52 出处:网络
Hey all, basically, i have an array: array(\'a\', \'b\', \'c\'); Now i run it through an array permutation function and the result is:

Hey all, basically, i have an array:

array('a', 'b', 'c');

Now i run it through an array permutation function and the result is:

Array
(
    [0] => Array
        (
            [0] => C
        )

    [1] => Array
        (
            [0] => B
        )

    [2] => Array
        (
            [0] => B
            [1] => C
        )

    [3] => Array
        (
            [0] => C
            [1] => B
        )

    [4] => Array
        (
            [0] => A
        )

    [5] => Ar开发者_C百科ray
        (
            [0] => A
            [1] => C
        )

    [6] => Array
        (
            [0] => C
            [1] => A
        )

    [7] => Array
        (
            [0] => A
            [1] => B
        )

    [8] => Array
        (
            [0] => B
            [1] => A
        )

    [9] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

    [10] => Array
        (
            [0] => A
            [1] => C
            [2] => B
        )

    [11] => Array
        (
            [0] => B
            [1] => A
            [2] => C
        )

    [12] => Array
        (
            [0] => B
            [1] => C
            [2] => A
        )

    [13] => Array
        (
            [0] => C
            [1] => A
            [2] => B
        )

    [14] => Array
        (
            [0] => C
            [1] => B
            [2] => A
        )

)

Now my question is, how can i clean that array up so that:

array ( C, B )
is the same as
array ( B, C )

and it removes the second array

How would i do that?

EDIT... after some research based on your answers, this is what I came up with:

array_walk($array, 'sort');
$array = array_unique($array);

sort($array); // not necessary


Just sort the constituent arrays:

foreach ($arrays AS &$arr)
{
   sort($arr);
}

So {"C", "B"} becomes => {"B", "C"}
and {"B", "C"} becomes => {"B", "C"}

which are identical.


array_multisort($array);
array_unique($array);


You can also use the pear package Math_Combinatorics.

require_once 'Combinatorics.php';
$combinatorics = new Math_Combinatorics;
$a = array('a', 'b', 'c');

// creating and storing the combinations
for($combinations = array(), $n=1; $n<=count($a); $n++) {
  $combinations = array_merge($combinations, $combinatorics->combinations($a, $n));
}

// test output
foreach($combinations as $c) {
  echo join(', ', $c), "\n";
}

prints

a
b
c
a, b
a, c
b, c
a, b, c
0

精彩评论

暂无评论...
验证码 换一张
取 消