kaito kid
kaito kid

Reputation: 11

how to use recursion for nested foreach with each key in array

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

Upvotes: 0

Views: 210

Answers (1)

LF-DevJourney
LF-DevJourney

Reputation: 28559

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

Upvotes: 1

Related Questions