user3856381
user3856381

Reputation: 33

PHP Dynamically Creating Nested Elements

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:

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.

Upvotes: 3

Views: 467

Answers (1)

FuzzyTree
FuzzyTree

Reputation: 32392

$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

Upvotes: 3

Related Questions