Home > other >  tree traversal to nth node
tree traversal to nth node

Time:09-28

I have a multidimensional array.

$tree= [
    "wood"=> [
      "segun",
      "koroi",
      "karosin"
    ],
    "food"=> [
        'grain',
        "vegetable"=> [
            "potato",
            "tomato"=>[
                "small"=>["cherri","local"],
                "big"=>["green","red"]
            ],
            "radish"
        ],
        "fruits"=> [
            "mango"=>[
              "lengra",
              "amrupali",
              "fozli",
                "him sagar"
            ],
            "jak fruits"
        ]
    ],
    "medicine"=> [
        "nim",
        "arjun",
        "amla"
    ],
    "oxygen",
    "computer"

];

I am using this code to show

function treeView($tree){
        $markup='';

        foreach ($tree as $key=>$value){

            $markup.= '<li>'. (is_array($value) ? $key. treeView($value) : $value) .'</li>';

        }
        return "<ul>".$markup."</ul>";
    }

I want to show upto 2 nodes of each element. This is not fixed, it can be nth nodes depends on user input. I am not getting it how to solve this.

If user input 3, I would like show the output like this

enter image description here

If user input 2, I would like show the output like this

enter image description here

CodePudding user response:

Just add an optional "defaults to 0" level parameter.

function treeView($tree, $max_level = 2, $current_level = 0)
{
    if ($max_level == $current_level) {
        return "";

    }
    $markup = '';

    foreach ($tree as $key => $value) {

        $markup .= '<li>' . (is_array($value) ? $key . treeView($value, $max_level, $current_level   1) : $value) . '</li>';

    }
    return "<ul>" . $markup . "</ul>";
}
  • Related