PHP数组构建-如何更好地编写它


PHP Array Building - How to write it better

我一直在绞尽脑汁,想如何写得更好,并根据$count值使其循环:

    if($count == 2){
        $thenode = $tree[$splitnode[0]][$splitnode[1]];
    } elseif($count == 3){
        $thenode = $tree[$splitnode[0]][$splitnode[1]][$splitnode[2]];
    }

有什么想法吗?谢谢

$thenode = $tree;
for ($i = 0; $i < $count; $i++) {
    $thenode = $thenode[$splitnode[$i]];
}
var_dump($thenode);

$thenode = array_reduce(
    range(0, $count - 1),
    function ($thenode, $i) use ($splitnode) { return $thenode[$splitnode[$i]]; },
    $tree
);

或者

$thenode = $tree;
foreach ($splitnode as $i => $sn) {
    if ($i >= $count) {
        break;
    }
    $thenode = $thenode[$sn];
}