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

你离开我真会死。 提交于 2019-12-25 05:05:17

问题


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


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


来源:https://stackoverflow.com/questions/44097359/how-to-use-recursion-for-nested-foreach-with-each-key-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!