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

时间:2013-12-11 09:21:41

标签: php arrays

如何更好地编写这个并根据$ count值使其循环:

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

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

$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];
}