PHP Clean Up Permutated Array

可紊 提交于 2020-01-14 06:21:39

问题


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] => Array
        (
            [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

回答1:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/1861966/php-clean-up-permutated-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!