从数组中查找组合

时间:2013-10-28 00:23:53

标签: php combinations permutation

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

我想打印出每个组合..像(乔,汤姆,丹),(乔,汤姆,玛丽),每个组合只从每个阵列中挑选1个。等等,直到没有更多的组合。在此之后我想将它们发布到我的网站上的3个帖子中。我知道该怎么做但我被困在这个组合部分。

很难解释..希望你能理解......

2 个答案:

答案 0 :(得分:0)

您可以使用3 for循环:

$combinations = new ArrayObject();
foreach ($array1 as $name1) {
    foreach ($array2 as $name2) {
        foreach ($array3 as $name3) {
            $combinations->append(array($name1, $name2, $name3));
        }
    }
}

答案 1 :(得分: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>';
}
?>