0

I have an array

$array = array(
        0 => array('a1', 'a2'),
        1 => array('b4', 'b3', 'b5'),
        2=> array('c1', 'c3'),
        3=> array('d2' , 'd5', 'd6')
);

I want to process the array as the program below :

$data= array();
$tmp = array();
foreach($array[0] as $arr0){
    $tmp[0]= $arr0;
    foreach($array[1] as $arr1){
        $tmp[1]= $arr1;
        foreach($array[2] as $arr2){
            $tmp[2]= $arr2;
            foreach($array[3] as $arr3){
                $tmp[3]= $arr3;
                $data[]= $tmp;
            }
        }
    }
}

print_r($data);

So how to use recursion for this program ?.

LF00
  • 27,015
  • 29
  • 156
  • 295
kaito kid
  • 11
  • 3

1 Answers1

1

Try this, check the live demo.

$result = [];
$temp = [];
foreach($array as $arr)
{
    foreach($arr as $v)
    {
        if($result == [])
          $temp[] = [$v];
        else{
        foreach($result as $val)
        {
          $val [] = $v;
          $temp[] = $val;
        }
        }
    }
    $result = $temp;
    $temp = [];
}
print_r($result);
LF00
  • 27,015
  • 29
  • 156
  • 295
  • it's just the order isuse. and my implementation is short of code than [your order implementation](https://eval.in/802254). If it helps please accept it and upvote it – LF00 May 21 '17 at 14:05
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Rizier123 May 21 '17 at 16:15