如何递归创建多维数组? [英] How to recursively create a multidimensional array?

查看:104
本文介绍了如何递归创建多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个多维数组,其部分由字符串确定.我正在使用.作为分隔符,并且每个部分(除了最后一个部分)都应该是一个数组
例如:

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) should be an array
ex:

config.debug.router.strictMode = true

我希望得到与输入相同的结果:

I want the same results as if I were to type:

$arr = array('config' => array('debug' => array('router' => array('strictMode' => true))));

这个问题的确使我陷入了困境,任何帮助我们都感激不尽.谢谢!

This problem's really got me going in circles, any help is appreciated. Thanks!

推荐答案

假设我们已经在$key$val中拥有键和值,那么您可以这样做:

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);

从左到右构建数组:

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

从右到左:

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

这篇关于如何递归创建多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆