0

Initially, I am afraid, that I do not find a better title for this question.

I have a two dimensional array that looks like this, for example:

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

i'd like now to convert/parse this into a two dimensional array that looks like this:

[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
    )

i hope you see, that the result should provide all sort of possible combinations. indeed, the length of the first array can differ.

i'd be interested in how to solve this algorithmically, but at the moment i have no idea.

i am not sure, if this is as easy as it looks like. thank you in advance.

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
emfi
  • 649
  • 6
  • 23

1 Answers1

0

I imagine this could be refined, but it should do the trick:

<?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);
?>
Philippe Sawicki
  • 852
  • 14
  • 22
GemmaB89
  • 165
  • 2
  • 16