如何使用PHP中每个组中的两个元素从数组中获取所有可能的组合?

时间:2016-08-17 13:58:11

标签: php arrays logic

我陷入困境,让我的大脑努力解决这个问题。 我有这个数组:

$options = array(
  'Group 1' => array( 'Track 1', 'Track 2', 'Track 3'),
  'Group 2' => array( 'Track 4', 'Track 5', 'Track 6'),
  'Gruop 3' => array( 'Track 7', 'Track 8', 'Track 9'),
  'Group 4' => array( 'Track 10', 'Track 11', 'Track 12'),
  'Group 5' => array( 'Track 13', 'Track 14', 'Track 15')
);

我需要使用每个组中的两个元素按照ascendent顺序创建一组完整的10个元素,并避免使用与另一个元素相同的元素集,如下例所示:

我实际上只能从每个组中获得一个项目:

function create_set( $t, $terms, $i ) {
    $text = '';
    if ( $i >= count( $terms ) ) {
        $text .= trim( $t ) . "\n";
    }
    else {
        foreach ( $terms[$i] as $term ) {
            $text .= create_set( $t . $term . '##', $terms, $i + 1 );
        }
    }

    return $text;
}

$options = array(
 'Group 1' => array( 'I am track 1', 'I am track 2', 'I am track  3'),
 'Group 2' => array( 'I am track 4', 'I am track 5', 'I am track 6'),
 'Gruop 3' => array( 'I am track 7', 'I am track 8', 'I am track 9'),
 'Group 4' => array( 'I am track 10', 'I am track 11', 'I am track 12'),
 'Group 5' => array( 'I am track 13', 'I am track 14', 'I am track 15')
);

$combine = array();
foreach( $options as $k => $v ) {
    $combine[] = $v;
}

$text = create_set( '', $combine, 0 );
$text = preg_split( '/\n/', $text, -1, PREG_SPLIT_NO_EMPTY );
$combinations = array();
foreach( $text as $k => $v ) {
   $combinations[] = preg_split( '/##/', $v, -1, PREG_SPLIT_NO_EMPTY );
}
echo "<pre>";
print_r( $combinations );
echo "</pre>";
exit;   

结果:

 Array
(
[0] => Array
    (
        [0] => I am track 1
        [1] => I am track 4
        [2] => I am track 7
        [3] => I am track 10
        [4] => I am track 13
    )

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

由于我不知道输出的正确性如何,我创建了这段代码:

$result = [];
foreach ($options as $tracklist) {
    foreach (array_rand($tracklist, 2) as $key) {
        $result[] = 'I am '.$tracklist[$key];
    }
}

输出

Array
(
    [0] => I am Track 1
    [1] => I am Track 3
    [2] => I am Track 4
    [3] => I am Track 5
    [4] => I am Track 7
    [5] => I am Track 9
    [6] => I am Track 11
    [7] => I am Track 12
    [8] => I am Track 13
    [9] => I am Track 14
)