简体   繁体   中英

Nested list from two-dimensional Array

I want to create a nested list in HTML (with ul and li) out of a two-dimensional array.

The array looks like this:

myArray["1"]["name"] -> Apple
myArray["1"]["parent"] -> 2
myArray["2"]["name"] -> Fruits
myArray["2"]["parent"] -> 3
myArray["3"]["name"] -> Food
myArray["3"]["parent"] -> (empty)
myArray["4"]["name"] -> Water
myArray["4"]["parent"] -> 5
myArray["5"]["name"] -> Drinks
myArray["5"]["parent"] -> (empty)
myArray["6"]["name"] -> Milk
myArray["6"]["parent"] -> 5

And now i want to find all these relations (also more layers) and dispaly them with HTML list elements:

    $allObjects = db_getAll();

    function r($parent, $arrayAllObjects){

        foreach ($arrayAllObjects as $object) {
            if ($object["parent"]==$parent) {
                return ("<ul>".$object["name"]."<li>". r($object["ID"], $arrayAllObjects)."</li></ul>");
            }
        }
    }


    echo r("0", $allObjects);

It starts good and the first "branch/arm" is displayed perfectly but after that (the first leaf at the end) it stops :(

Current Result:

 -Food
  -Fruits
   -Apple

Missing:

 -Drinks
  -Water
  -Milk
 -Example
  -Test
   -Test
   -...
 -...

What did I forget?

Thank you so much!

The problem is that after processing the first item at the base layer, you then return inside the foreach loop which means that it won't go onto any further items.

Instead you need to build up all of the output and return this from the end of the function...

function extractLayer($parent, $arrayAllObjects){
    $output = "";
    foreach ($arrayAllObjects as $object) {
        if ($object["parent"]==$parent) {
            $subLayer = extractLayer($object["ID"], $arrayAllObjects);
            if ( !empty($subLayer) )    {
                $output .="<ul>".$object["name"].$subLayer."</ul>";
            }
            else    {
                $output .= "<li>".$object["name"]."</li>";
            }
        }
    }
    return $output;
}

echo extractLayer("0", $allObjects);

I've also changed the function name as r isn't obvious.

Just updated this as each leaf was also building a list of it's own even if there were no sub layers. So this checks for sub layers and if there aren't any, it just puts the item in <li> tags.

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