3

I am creating an array from a query using various tables that gives me a variable number of parents each containing a variable number of values.

For simplicity, say I have the following (using p as parent and v as value):

$parent[0] = array("p1v1","p1v2");  
$parent[1] = array("p2v1","p2v2","p2v3");  
$parent[2] = array("p3v1","p3v2");

I need to created the following tree:

  • p1v1
    • p2v1
      • p3v1
      • p3v2
    • p2v2
      • p3v1
      • p3v2
    • p2v3
      • p3v1
      • p3v2
  • p1v2
    • p2v1
      • p3v1
      • p3v2
    • p2v2
      • p3v1
      • p3v2
    • p2v3
      • p3v1
      • p3v2

Nested foreach loops:

foreach ($parent[0] as $key1 => $value1) {
    echo $value1 . '<br />';
    foreach ($parent[1] as $key2 => $value2) {
        echo '-- ' . $value2 . '<br />';
        foreach ($parent[2] as $key3 => $value3) {
            echo '---- ' . $value3 . '<br />';
        }
    }
}

I can do this with nested foreach loops as above but my problem is that I don't know how many parents I will have for a given query. So, how can I create a variable number of nested foreach loops... I am sure there is a better way.

Thanks for any input/advice.

1
  • That's what recursion is for. Commented Jul 19, 2014 at 18:38

1 Answer 1

3
$parent[0] = array("p1v1","p1v2");  
$parent[1] = array("p2v1","p2v2","p2v3");  
$parent[2] = array("p3v1","p3v2");

function print_nested_array($parent,$level=0) {
    foreach($parent[$level] as $value) {        
        if($level > 0) {
            foreach(range(0,$level-1) as $j) {
                echo '--';
            }

            echo ' ';
        }            

        echo $value . "\n"; //change to "<br>" for html

        if($level < count($parent)-1)
            print_nested_array($parent,($level+1));
    }
}

print_nested_array($parent,0);

Demo

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.