2016-03-02 70 views
3

以下數組給我多個「選項」(類型,純度,模型)。請記住,「選項」可能在循環的下一次迭代中增加或減少。PHP嵌套在多維數組上的foreach

$options = array(
    'type' => array('Old', 'Latest', 'GOLD 1.0', 'GOLD 1.1', 'GOLD 1.2', 'GOLD 1.3'), 
    'purity' => array('GOLD', 'SILVER', 'BRONZE'), 
    'model' => array('Rough', 'Neat', 'mixed', 'Random'), 
); 

我想達到的輸出是

Old GOLD Rough 
Old GOLD Neat 
Old GOLD mixed 
Old GOLD Random 

Old SILVER Rough 
Old SILVER Neat 
Old SILVER mixed 
Old SILVER Random 

Old BRONZE Rough 
Old BRONZE Neat 
Old BRONZE mixed 
Old BRONZE Random 

Then this whole scenario goes for 'Latest', 'GOLD 1.0', 'GOLD 1.1', 
'GOLD 1.2' and 'GOLD 1.3'(each element of first array) 

This way it will generate total 72 combinations (6 * 3 * 4) 

什麼,我都取得了這麼遠。

如果我有靜態的「選項」(類型,純度,型號),我可以使用嵌套的foreach即

$type = array('Old', 'Latest', 'GOLD 1.0', 'GOLD 1.1', 'GOLD 1.2', 'GOLD 1.3'); 
$purity = array('GOLD', 'SILVER', 'BRONZE'); 
$model = array('Rough', 'Neat', 'mixed', 'Random'); 

foreach($type as $base){ 
       foreach($purity as $pure){ 
        foreach($model as $mdl){ 
      echo $base.' '.$pure.' '.$mdl.'<br />'; 

    } 
    } 
} 

但我不知道我應該有多少個foreach循環使用,作爲「選項」可減少或增加。所以我必須動態地通過數組。任何幫助將不勝感激 謝謝

+0

你有3個陣列,從你的例子中不清楚你是如何聯繫他們。它們都是不同的尺寸。 –

+0

@Muhammed M. 選項和值來自DB '$ options = array( 'type'=> array('Old','Latest','GOLD 1.0','GOLD 1.1','GOLD 'GOLD''', 'purity'=> array('GOLD','SILVER','BRONZE'), 'model'=> array('Rough','Neat','mixed', 'Random'), );' 假設在下一次迭代中它可能沒有'model',或者它可能會在'$ options'數組中添加一些其他數組。所以這個數組的大小可能會增加或減少。 我想從'$ options'數組內的數據實現組合。 –

+0

如果選項增加,你的意思是什麼?你能舉個例子嗎?請編輯你的anwer,我們會解決你的問題。現在輸出是3列,如果你添加另一個選項輸出將是4列正確?所以基本上,輸出中的列數是選項數組的大小,對嗎?輸出結果應該是:column1,column2,column3 ....列N - >全部與$ options [0],$ options [1] ... $ options [N-1]匹配,是否正確? –

回答

1
$options = array(
    'type' => array('Old', 'Latest', 'GOLD 1.0', 'GOLD 1.1', 'GOLD 1.2', 'GOLD 1.3'), 
    'purity' => array('GOLD', 'SILVER', 'BRONZE'), 
    'model' => array('Rough', 'Neat', 'mixed', 'Random'), 
); 

// Create an array to store the permutations. 
$results = array(); 
foreach ($options as $values) { 
    // Loop over the available sets of options. 
    if (count($results) == 0) { 
     // If this is the first set, the values form our initial results. 
     $results = $values; 
    } else { 
     // Otherwise append each of the values onto each of our existing results. 
     $new_results = array(); 
     foreach ($results as $result) { 
      foreach ($values as $value) { 
       $new_results[] = "$result $value"; 
      } 
     } 
     $results = $new_results; 
    } 
} 

// Now output the results. 
foreach ($results as $result) { 
    echo "$result<br />"; 
} 
+0

非常感謝你。你救了我的一天:) –