dpspn60064 2015-10-17 22:55
浏览 40
已采纳

迭代通过多维数组

I have an array with this structure:

Array ( 
[0] => Array ( [key] => Egg Method [values] => Array ( 
    [0] => Array ( [id] => 1 [value] => Boiled ) 
    [1] => Array ( [id] => 2 [value] => Poached ) 
    [2] => Array ( [id] => 3 [value] => Fried ) 
    [3] => Array ( [id] => 4 [value] => Scrambled ) ) ) 

[1] => Array ( [key] => Bread [values] => Array ( 
    [0] => Array ( [id] => 5 [value] => White ) 
    [1] => Array ( [id] => 6 [value] => Brown ) ) ) 

[2] => Array ( [key] => Egg Hardness [values] => Array ( 
    [0] => Array ( [id] => 7 [value] => Soft ) 
    [1] => Array ( [id] => 7 [value] => Medium )    
    [2] => Array ( [id] => 8 [value] => Hard ) ) ) 

)

How could I iterate through the array to output all of the possible permutations, i.e.

Egg Method: Boiled / Bread: White / Egg Hardness: Soft
Egg Method: Boiled / Bread: White / Egg Hardness: Medium
Egg Method: Boiled / Bread: White / Egg Hardness: Hard
Egg Method: Boiled / Bread: Brown / Egg Hardness: Soft
Egg Method: Boiled / Bread: Brown / Egg Hardness: Medium
Egg Method: Boiled / Bread: Brown / Egg Hardness: Hard
Egg Method: Poached / Bread: White / Egg Hardness: Soft
Egg Method: Poached / Bread: White / Egg Hardness: Medium
Egg Method: Poached / Bread: White / Egg Hardness: Hard
Egg Method: Poached / Bread: Brown / Egg Hardness: Soft
Egg Method: Poached / Bread: Brown / Egg Hardness: Medium
Egg Method: Poached / Bread: Brown / Egg Hardness: Hard
etc etc

One additional problem is I don't know how many criteria arrays there might be, so unfortunately I can't just use 3 nested loops for this.

I am using PHP, although I guess a pseudo code solution will be fine and I can adapt it.

  • 写回答

2条回答 默认 最新

  • dongrang2140 2015-10-19 10:31
    关注

    Solved it

    recurse("", $partoptions, 0);
    
    function recurse($longstring, $partoptions, $index) {
        $key = $partoptions[$index]['key'];
        $values = $partoptions[$index]['values'];   
        for ($i=0; $i<sizeof($values); $i++) {                  
            $thisvalue = $values[$i]['value'];  
            if (sizeof($partoptions)>$index+1) {
                $tmplongstring = $longstring . ($longstring==""?"":" / ") . $thisvalue;
                recurse($tmplongstring, $partoptions, $index+1);
            } else {
                echo $longstring . " / " . $thisvalue . "<br>";
            }           
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ 如何判断设置快捷键来实现隐藏/显示窗口
  • ¥15 关于#材料工程#的问题:有没有具有电子阻挡层和空穴阻挡层的电池仿真silvaco代码例子或者其他器件具有阻挡层例子的silvaco代码(最好还有相关文献)
  • ¥60 基于MATLAB的TAOD算法
  • ¥15 Groimp使用疑问
  • ¥15 MDK–ARM里一直找不到调试器
  • ¥15 oracle中sql查询问题
  • ¥15 vue使用gojs3.0版本,在nodeDataArray中的iconSrc使用gif本地路径,展示出来后动画是静态的,不是动态的
  • ¥100 代写个MATLAB代码,有偿
  • ¥15 ansys electronics 2021 R1安装报错,错误代码2,如图
  • ¥15 Dev-c++打字不出现中文,但出现日文