2009-12-07 54 views
0

嘿,基本上,我有一個數組:PHP清理置換陣列

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

現在我運行它通過陣列排列的功能,其結果是:

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 
     ) 

) 

現在的問題是,如何清潔該陣列向上,以便:

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

並刪除所述第二陣列

我該怎麼做?

編輯...根據您的回答經過一番研究,這是我想出了:

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

sort($array); // not necessary 
+1

爲什麼你就不能更換組合功能置換功能? – philfreo 2009-12-07 18:35:40

+0

因爲我沒有編寫排列函數,因爲算法讓我感到困惑:P – Ozzy 2009-12-07 18:38:02

回答

3

只是sort組成的數組:

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

所以{ 「C」, 「B」}變成=> {「B」,「C」}
並且{「B」,「C」}變成=> {「B」,「C」}

它們是相同的。

+1

對數組排序後,您需要使用array_unique()來刪除重複項。 http://us.php.net/manual/en/function.array-unique.php – 2009-12-07 18:37:06

+0

謝謝道格和搶,結合你們倆說的完美工作:) – Ozzy 2009-12-07 18:40:14

+0

謝謝,我推薦hsz的回答。它更乾淨。 – 2009-12-07 19:34:54

3
array_multisort($array); 
array_unique($array); 
+0

不知道multisort,+1。 – 2009-12-07 18:39:16

+0

立即檢查。 :) – hsz 2009-12-07 18:41:49

1

您還可以使用梨包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"; 
} 

打印

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