php生成给定数组的所有组合

时间:2013-07-30 08:47:24

标签: php combinations

转换此PHP数组

的最简单方法是什么?
$a = array('A' => array(1, 2),
           'B' => array(3, 4),
           'C' => array(5));

进入这个:

$result = array(
    array('A' => 1, 'B' => 3, 'C' => 5),
    array('A' => 1, 'B' => 4, 'C' => 5),
    array('A' => 2, 'B' => 3, 'C' => 5),
    array('A' => 2, 'B' => 4, 'C' => 5),
);

$a在开发期间可能会有许多不同的keys我不知道。所以我需要 生成给定数组中的所有组合。

更新

我必须根据传入的数组生成URLs。所以我不知道在开发期间会得到多少参数。我只有参数数组,例如。

$a = array('A' => array(5,3, 1));

结果将是:

$result = array(
    array('A' => 5),
    array('A' => 3),
    array('A' => 1));

$a = array('X' => array(5), 'D' => array(4, 7));

结果将是:

$result = array(
    array('X' => 5, 'D' => 4),
    array('X' => 5, 'D' => 7));

2 个答案:

答案 0 :(得分:6)

喜欢这个:

$a = array('A' => array(1, 2),
           'B' => array(3, 4),
           'C' => array(5));

function get_combinations($arrays) {
    $result = array(array());
    foreach ($arrays as $property => $property_values) {
        $tmp = array();
        foreach ($result as $result_item) {
            foreach ($property_values as $property_value) {
                $tmp[] = array_merge($result_item, array($property => $property_value));
            }
        }
        $result = $tmp;
    }
    return $result;
}

输出

var_dump(get_combinations($a));

array (size=4)
  0 => 
    array (size=3)
      'A' => int 1
      'B' => int 3
      'C' => int 5
  1 => 
    array (size=3)
      'A' => int 1
      'B' => int 4
      'C' => int 5
  2 => 
    array (size=3)
      'A' => int 2
      'B' => int 3
      'C' => int 5
  3 => 
    array (size=3)
      'A' => int 2
      'B' => int 4
      'C' => int 5

答案 1 :(得分:0)

您可以将此功能用于此请求:

function pc_array_power_set($array) {
    // initialize by adding the empty set
    $results = array(array( ));

    foreach ($array as $element)
        foreach ($results as $combination)
            array_push($results, array_merge(array($element), $combination));

    return $results;
}

用法:

$set = array('A', 'B', 'C');
$power_set = pc_array_power_set($set);

输出:

array( );
array('A');
array('B');
array('C');
array('A', 'B');
array('A', 'C');
array('B', 'C');
array('A', 'B', 'C');

资源:http://docstore.mik.ua/orelly/webprog/pcook/ch04_25.htm