2015-05-13 31 views
0

最初,我擔心,我沒有爲這個問題找到更好的標題。如何創建二維數組的排列

我有一個二維數組,它看起來像這樣,例如:

[0] => Array 
    (
     [0] => 10,00 
    ) 
[1] => Array 
    (
     [0] => 3 
     [1] => 4 
    ) 
[2] => Array 
    (
     [0] => true 
     [1] => false 
    ) 

我現在想轉換/解析此爲二維數組,看起來像這樣:

[0] => Array 
    (
     [0] => 10,00 
     [1] => 3 
     [2] => true 
    ) 
[1] => Array 
    (
     [0] => 10,00 
     [1] => 4 
     [2] => true 
    ) 
[2] => Array 
    (
     [0] => 10,00 
     [1] => 3 
     [2] => false 
    ) 
[3] => Array 
    (
     [0] => 10,00 
     [1] => 4 
     [2] => false 
    ) 

我希望你看到,結果應該提供各種可能的組合。事實上,第一個陣列的長度可能不同。

我會對如何解決這個算法感興趣,但目前我不知道。

我不確定,如果這看起來很簡單。先謝謝你。

+0

你已經嘗試到現在什麼。請給我們看? –

+0

爲什麼你在關鍵'[2]'中有'true'或'false',它代表什麼以及它爲什麼會改變? – VeeeneX

+0

謝謝你kolmar,這對我有很大的幫助 – emfi

回答

0

我想這可能是精緻,但它應該做的伎倆:

<?php 

$arrStart = array(
    array('10,00'), 
    array(3, 4), 
    array('true', 'false') 
); 

$arrPositions = array(); 
$arrResult = array(); 

//get a starting position set for each sub array 
for ($i = 0; $i < count($arrStart); $i++) 
    $arrPositions[] = 0; 

//repeat until we've run out of items in $arrStart[0] 
while (array_key_exists($arrPositions[0], $arrStart[0])) { 
    $arrTemp = array(); 
    $blSuccess = true; 

    //go through each of the first array levels 
    for ($i = 0; $i < count($arrStart); $i++) { 
     //is there a item in the position we want in the current array? 
     if (array_key_exists($arrPositions[$i], $arrStart[$i])) { 
      //add that item to our temp array 
      $arrTemp[] = $arrStart[$i][$arrPositions[$i]]; 
     } else { 
      //reset this position, and raise the one to the left 
      $arrPositions[$i] = 0; 
      $arrPositions[$i - 1]++; 
      $blSuccess = false; 
     } 
    } 

    //this one failed due to there not being an item where we wanted, skip to next go 
    if (!$blSuccess) continue; 

    //successfully adding nex line, increase the right hand count for the next one 
    $arrPositions[count($arrStart) - 1]++; 

    //add our latest temp array to the result 
    $arrResult[] = $arrTemp; 
} 

print_r($arrResult); 
?>