Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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.

share|improve this question

1 Answer 1

up vote 0 down vote accepted
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
share|improve this answer
    
Looks very good man, Thank you very much! I can't say how happy I am to see a working example. Now i need to study this hard. – Pontus Nilsson Feb 19 at 22:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.