PHP ::获取数组中的所有可用选项

时间:2017-03-15 08:36:51

标签: php arrays string loops for-loop

我的大脑着火了:'(

我希望从$元音中获取所有可用选项,但不会在同一行中重复相同的字母。

<?php

$vowels=array("A","E","I","O","U");

$row=3;
$column=3;

echo '<pre>';

do{

        foreach ($vowels as &$value)
        {

                 //Magic Goes Here :P
        }

        $row--;

}while($row<>0);

echo '</pre>';

所以(例如)因为这里有5个选项(&#34; A&#34;,&#34; E&#34;,&#34; I&#34;,&#34; O&#34 ;,&#34; U&#34;)但是行数限制为3,单行中的最大选项/ S为3,但为了简单起见,我们假设:

$row=2;
$column=2;

所以结果:

AE

EA

AI

IA

AO

OA

AU

UA

EA

AE

EI

IE

EO

OE

EU

UA

IA

AI

IE

IO

IU

UI

...等 感谢您提前帮助! :)

2 个答案:

答案 0 :(得分:2)

<?php

$vowels=array("A","E","I","O","U");

echo '<pre>';

    foreach ($vowels as $value)
    {
        foreach ($vowels as $value1){
            if($value1 != $value)
                echo $value.$value1.'<br>';     
        }
    }

echo '</pre>';

答案 1 :(得分:1)

我建议使用递归:

function recurrency($vowels, $cols, $level, $used) {
    $i = -1; // EDIT to make loop index increment in one place
    foreach ($vowels as $value) {
        $i++;
        if (in_array($i, $used)) {
            continue;
        }
        $newUsed = $used;
        $newUsed[] = $i;
        if ($level < $cols && count($vowels) > $level) {
            recurrency($vowels, $cols, $level + 1, $newUsed);
        } else {
            foreach ($newUsed as $index) {
                echo $vowels[$index];
            }
            echo "<br />\n";
        }
        if ($level == 1) {
            echo "<hr />\n\n";
        }
    }
}

$vowels=array("A","E","I","O","U");

$row=3;
$column=3;

echo '<pre>';

recurrency($vowels, $column, 1, []);

echo '</pre>';

这不是很明确的解决方案,我没有得到如何使用变量$row,但我想这是你要问的想法。