【问题标题】:How to generate Combinations of fixed size from multiple arrays?如何从多个数组生成固定大小的组合?
【发布时间】:2016-05-20 01:18:39
【问题描述】:

我需要在具有固定子集大小的几个数组中找到所有项目组合。例如,我有 3 个数组:

$A = array('A1','A2','A3');
$B = array('B1','B2','B3');
$C = array('C1','C2','C3');

我想从上述数组中生成大小为 2 的组合。喜欢:

$Combinations = array(
    [0] => array('A1', 'B1'),
    [1] => array('A1', 'C1'),
    [2] => array('A2', 'B1'),
    [3] => array('A2', 'C1')
);

这个solution 正在生成所有组合,但其中似乎没有大小参数。

寻求帮助!

【问题讨论】:

  • 尝试在一个循环中使用两个循环。
  • @Rishi:你能详细说明一下吗?
  • 已给出解决方案

标签: php arrays combinations


【解决方案1】:
$A = array('A1','A2','A3');
$B = array('B1','B2','B3');
$C = array('C1','C2','C3');
$All = array();
 foreach ($A as $key1=>$value1){
 foreach ($B as $key2=>$value2){
     $All[] = array($value1,$value2 );
 }
 foreach ($C as $key3=>$value3){
     $All[] = array($value1,$value3 );
 }
 }

 print_r($All);

在此处检查输出:https://eval.in/574060

【讨论】:

  • 你想这样创作?
【解决方案2】:

终于找到了解决办法。使用以下脚本,您可以将任意数量的数组与任意数量的元素组合在一起。请阅读代码中的 cmets 并尝试了解会发生什么。

<?php
$A = array('A1', 'A2', 'A3');
$B = array('B1', 'B2', 'B3');
$C = array('C1', 'C2', 'C3');

$combinationCount = 5;
$itemsPerCombination = 2;
$array = ['A', 'B', 'C'];

$combinations = array();
for ($x = 0; $x < $combinationCount; $x++) {
    //to keep temporary names of arrays which come in a combination
    $arrays = array();
    for ($y = 0; $y < $itemsPerCombination; $y++) {
        $valid = false;
        while (!$valid) {
            //get a random array, check if it is already in our selection
            $arrayElement = $array[rand(0, count($array) - 1)];
            if (in_array($arrayElement, $arrays)) {
                $valid = false;
                continue;
            }
            $arrays[] = $arrayElement;
            $valid = true;
        }
    }

    $found = false;
    while (!$found) {
        //for each selection in our selected arrays, take a random element and add to the combination.
        $combination = array();
        foreach ($arrays as $arr) {
            $temp=$$arr;
            $combination[] = $temp[rand(0, count($temp) - 1)];
        }
        if (in_array($combination, $combinations)) {
            $found = false;
            continue;
        }
        $combinations[] = $combination;
        $found = true;
    }
}
echo(json_encode($combinations));
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多