0
$array1=["joe","bob"];
$array2=["tom","bill"];
$array3=["dan","mary"];

I want to print out every combination.. like (joe,tom,dan),( joe,tom,mary), only picking 1 from each array for each combination. and so on until there are no more combinations. After this i want to post them onto 3 post forms on my website.. I know how to do that but I am stuck on this combination part.

Hard to explain.. hope you have understood..

4

2 回答 2

0

当没有声望是不允许的

<?php

$array1=["joe","bob"];
$array2=["tom","bill"];
$array3=["dan","mary"];

$arr = array_merge($array1,$array2,$array3);
$result = array();

function noRepeatation($arr, $temp_string, &$collect) {
    if ($temp_string != "") 
        $collect []= $temp_string;

    for ($i=0; $i<sizeof($arr);$i++) {
        $arrcopy = $arr;
        $elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
        if (sizeof($arrcopy) > 0) {
            noRepeatation($arrcopy, $temp_string ." " . $elem[0], $collect);
        } else {
            $collect []= $temp_string. " " . $elem[0];
        }   
    }   
}

$collect = array();
noRepeatation($arr, "", $collect);
print_r($collect);
?>

允许声誉时

<?php
$array1=["joe","bob"];
$array2=["tom","bill"];
$array3=["dan","mary"];

$arr = array_merge($array1,$array2,$array3);
$result = array();

function repeatation($arr, $level, &$result, $curr=array()) {
    for($i = 0; $i < count($arr); $i++) {
        $new = array_merge($curr, array($arr[$i]));
        if($level == 1) {
            sort($new);
            if (!in_array($new, $result)) {
                $result[] = $new;          
            }
        } else {
            repeatation($arr, $level - 1, $result, $new);
        }
    }
}

for ($i = 0; $i<count($arr); $i++) {
    repeatation($arr, $i+1, $result);
}

foreach ($result as $arr) {
    echo join(" ", $arr) . '<br>';
}
?>
于 2013-10-28T01:24:37.743 回答
0

您可以使用 3 个 for 循环:

$combinations = new ArrayObject();
foreach ($array1 as $name1) {
    foreach ($array2 as $name2) {
        foreach ($array3 as $name3) {
            $combinations->append(array($name1, $name2, $name3));
        }
    }
}
于 2013-10-28T00:43:45.013 回答