【问题标题】:Find combinations from Arrays [closed]从数组中查找组合[关闭]
【发布时间】:2013-10-28 00:23:53
【问题描述】:
$array1=["joe","bob"];
$array2=["tom","bill"];
$array3=["dan","mary"];

我想打印出每个组合.. 像 (joe,tom,dan),(joe,tom,mary),只为每个组合从每个数组中挑选 1 个。依此类推,直到没有更多的组合。在此之后,我想将它们发布到我网站上的 3 个帖子表单上。我知道该怎么做,但我被困在这个组合部分。

很难解释..希望你明白..

【问题讨论】:

  • 是否允许重复。 ?
  • 是的。我相信排列对我来说是正确的术语。

标签: php combinations permutation


【解决方案1】:

您可以使用 3 个 for 循环:

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

【讨论】:

  • var_dump($combinations);它给了我一个大网格 (gyazo.com/459a17ed0e456ec598e6fb3cb65cd77d)。由于我尝试使用 cURL 发布每个数组,因此我可以以任何方式将其作为每个组合的数组回显吗?
  • 这是一个数组数组。每个数组都是 [name1, name2, name3] 的组合。它已经是每个组合的一个数组:$combinations[0] 这是第一个组合,$combinations[1] 第二个等等。您可以“很好”打印它,例如使用 foreach ($combinations as $c) { print join($c, ", ") . "\n"; }
  • 你是救生员。你能解释一下 append() 吗?看不懂php.net的解释
  • 它只是在末尾添加元素。与$combinations[] = new_element 相同;只是我来自没有这种语法的python,而append()被大量使用:)
【解决方案2】:

当没有声望是不允许的时候

<?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>';
}
?>

【讨论】:

  • 你们俩都太好了!我希望我能给你们两个正确的答案!
  • @user2318029 如果你愿意,你也可以投票
  • 相信我我试过了。我需要 15 声望。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多