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 ?.

8
  • 1
    You just want to print the array keys? your question isn't clear to me. Commented May 21, 2017 at 13:20
  • Learning recursion works best when you attempt to do it, fail and have a specific question instead of a request for someone to do it for you. :) Commented May 21, 2017 at 13:24
  • You posted only a 2-dimensional array, why would you iterate it 4 layers deep? Commented May 21, 2017 at 13:24
  • @ccKep - Look at it again, the first loop may be unnecessary or produce unexpected results. Commented May 21, 2017 at 13:25
  • 1
    Possible duplicate of All possible combinations in array - recursion? Commented May 21, 2017 at 13:29

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

it's just the order isuse. and my implementation is short of code than your order implementation. If it helps please accept it and upvote it
While this code snippet may solve the question, including an explanation 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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.