How to recursively create a multidimensional array?

前端 未结 5 1768
无人及你
无人及你 2020-12-17 06:47

I am trying to create a multi-dimensional array whose parts are determined by a string. I\'m using . as the delimiter, and each part (except for the last) shoul

5条回答
  •  难免孤独
    2020-12-17 07:35

    Let’s assume we already have the key and value in $key and $val, then you could do this:

    $key = 'config.debug.router.strictMode';
    $val = true;
    $path = explode('.', $key);
    

    Builing the array from left to right:

    $arr = array();
    $tmp = &$arr;
    foreach ($path as $segment) {
        $tmp[$segment] = array();
        $tmp = &$tmp[$segment];
    }
    $tmp = $val;
    

    And from right to left:

    $arr = array();
    $tmp = $val;
    while ($segment = array_pop($path)) {
        $tmp = array($segment => $tmp);
    }
    $arr = $tmp;
    

提交回复
热议问题