从 3 个带有 id 的列表进行组合


Making combinations from 3 lists with id's

我有这个系统,其中包含配置项和由这些配置项组成的组合。我试图实现的是选择尚未进行的组合。

系统示例:

苹果 ID 的配置: 1, 2, 3

配置对等 ID:4,5,6,7,8

配置芒果ID:9,10,11,12,13

组合总是按苹果、同行和芒果的顺序排列。

现在,我尝试完成可用配置项的所有可能组合。

因此:苹果ID:1对等 ID:4芒果ID:9

另一种组合:苹果ID:1对等 ID:4芒果 ID: 10

诸如此类。

我想知道如何从苹果,同行和芒果ID中制作所有可能的组合。

希望我能清楚地描述它。我不知道如何做到这一点,但我的第一个猜测是:

$apples = array();
query select appleid FROM apples
while($apples_sql = mysqli_fetch_assoc($result)) {
{
 $apples[] =  $row["appleid"];
}
$peers = array();
query select peerid FROM peers
while($peers_sql = mysqli_fetch_assoc($result)) {
{
 $peers[] =  $row["peerid"];
}
$mango = array();
query select mangoid FROM mango
while($mango_sql = mysqli_fetch_assoc($result)) {
{
 $mango[] =  $row["mangoid"];
}

然后我把所有的苹果、同行和芒果 ID 放在一个数组中。但是我不知道如何进行组合。

希望有人可以帮助我。非常感谢任何帮助,提前感谢。

假设所有三个数组都有自己的 id使用嵌套 for 循环生成组合

for($a=0;$a<sizeof($apple);$a++){
  for($p=0;$p<sizeof($peers);$p++){
     for($m=0;$m<sizeof($mango);$m++){
   $combination=$apple[$a].",".$peers[$p].",".$mango[$m];
     echo $combination. "<br>";
}
}
}

我希望这会对您有所帮助

查看以下函数:

/**
 * Generate all the possible combinations among a set of nested arrays.
 *
 * @param array $data  The entrypoint array container.
 * @param array $all   The final container (used internally).
 * @param array $group The sub container (used internally).
 * @param mixed $val   The value to append (used internally).
 * @param int   $i     The key index (used internally).
 */
function generate_combinations(array $data, array &$all = array(), array $group = array(), $value = null, $i = 0)
{
    $keys = array_keys($data);
    if (isset($value) === true) {
        array_push($group, $value);
    }
    if ($i >= count($data)) {
        array_push($all, $group);
    } else {
        $currentKey     = $keys[$i];
        $currentElement = $data[$currentKey];
        foreach ($currentElement as $val) {
            generate_combinations($data, $all, $group, $val, $i + 1);
        }
    }
    return $all;
}
$apple = array(1,2,3);
$peer = array(4,5,6,7,8);
$mengo = array(9,10,11,12,13);
$data = array(
    $apple,
    $peer,
    $mengo,
);
$combos = generate_combinations($data);
print_r($combos);

$combos变量将具有 artray 格式的所有有效组合。