tree traversal to nth node

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.