简体   繁体   中英

php multidimensional array recursive

I have been searching very much and tried hard to get it to work but my brain can't just handle it. I'm calling out here to see if anyone can help me with this recursive function.

Example array:

$array = array(
            array(4),
            array(3,1),
            array(4,2,1)
        );

Expected output data:

434
432
431
424
422
421

My beginning:

function recursive($array){
    foreach($array as $key => $value){
        if(is_array($value)){
            recursive($value);
        } else{
            echo $value;
        }
    }
}

Output: 431421

I don't get it how to return all length multiple times.

Hope for help! Thanks.

Edit: Logic?

434
 12
  1

This is how it get the numbers from the start.
This means:
from the top, 434 is one combination
second row is subtract the number above it. so 3-1 = 2 ( 424 )
Third row is a subtract of the result for the first subtraction. like the last line is (4-2)-1 = 1 ( first 422. then 421 , but also 432 and 431
The expected output is all the possibilities of the numbers.

function walkme($array, $c) {
    if (!count($array)) {
            echo "$c\n";
            return;
    }
    $last=array_pop($array);
    foreach ($last as $l) {
            walkme($array, $l.$c);
    }
}

$array = array(
        array(4),
        array(3,2),
        array(4,2,1)
    );

walkme($array, "");

result:

434
424
432
422
431
421

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM