PHP排列,相似顺序除外

时间:2019-11-07 13:25:56

标签: php multidimensional-array permutation

我的数据排列/组合

$combinations = [[]];
$data = [

        ['alteration1', 'alteration2', 'alteration3', 'alteration4' ... upto 5 each],
        ['alteration1', 'alteration5', 'alteration6', 'alteration7' ... upto 5 each],
        ['alteration8', 'alteration9', 'alteration10', 'alteration5' ... upto 5 each],
        ... upto 6 max
    ];

    $length = count($data);

    for ($count = 0; $count < $length; $count++) {
        $tmp = [];
        foreach ($combinations as $v1) {
            foreach ($data[$count] as $v2)
                $tmp[] = array_merge($v1, [$v2]);

        }
        $combinations = $tmp;
    }

  print_r($combinations);

脚本会生成这样的集合

 0 => array:3 [▼
    0 => "alteration1"
    1 => "alteration1"
    2 => "alteration8"
  ]
  1 => array:3 [▼
    0 => "alteration1"
    1 => "alteration1"
    2 => "alteration9"
  ]

...问题开始于当我开始在case数组索引0和20中获得相同的数据序列时,尽管它们处于任何位置都将完全相同。

 20 => array:3 [▼
        0 => "alteration8"
        1 => "alteration1"
        2 => "alteration1"
      ]
      21 => array:3 [▼
        0 => "alteration1"
        1 => "alteration9"
        2 => "alteration1"
      ]
 $final = []; // remove duplicates

基本思想是保持$ combinations数组的唯一(alteration1,alteration2,alteration3)等于(alteration3,alteration1,alteration2),然后在$ final数组中将其跳过。我还没有在SO和Google周围找到任何东西。谢谢您的帮助。 $ data dimentions [从1-6],内部的每个数组都可以是[1-6]。以下脚本可能无法按预期工作。

http://sandbox.onlinephpfunctions.com/code/3ad5084386c2185f7619aaac152b638873039ee8

1 个答案:

答案 0 :(得分:1)

  • 我们遍历数据并使用array_unique首先为每个集合查找唯一元素。

  • 然后我们natsort来获得它们的排序形式,并使用implode()对其进行序列化。这样,我们将为集合ABCCBABAC等获得相同的序列化代码。

  • 然后我们使用密钥检查变量$set中的重复项查找重复项。如果设置了序列化密钥,则将其从结果中排除,否则将其包括在最终结果中。

代码段:

<?php

$data = [
    ['alteration1', 'alteration4',],
    ['alteration2','alteration3'],
    ['alteration2','alteration3'],
    []
];


$combinations = [[]];

foreach($data as $index => $current_data){
   $current_data = array_unique($current_data);   
   if(empty($current_data)) continue; 
   $temp_combinations = [];
   foreach($current_data as $value){
       foreach($combinations as $each_combination){
           $temp_combinations[] = array_merge($each_combination,[$value]);
       }
   }

   $combinations = $temp_combinations;

}

$set = [];
$unique_combinations = [];

foreach($combinations as $each_combination){
    natsort($each_combination);
    $serialized_form = implode(",",$each_combination);
    if(isset($set[$serialized_form])) continue;
    if(empty($each_combination)) continue;
    $unique_combinations[] = $each_combination;
    $set[$serialized_form] = true;
}

print_r($unique_combinations);

演示: https://3v4l.org/Do6oH