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

config.debug.router.strictMode = true

我想要的结果与我输入的内容相同:

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

这个问题确实让我进入了圈子,任何帮助都表示赞赏。谢谢!

有帮助吗?

解决方案

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

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

其他提示

我说要把所有东西拆开,从值开始,然后从那里向后工作,每次都将你在另一个数组中包含的内容包装起来。像这样:

$s = 'config.debug.router.strictMode = true';
list($parts, $value) = explode(' = ', $s);

$parts = explode('.', $parts);
while($parts) {
   $value = array(array_pop($parts) => $value);
}

print_r($parts);

绝对重写它,以便进行错误检查。

Gumbo的回答看起来不错。

但是,您似乎想要解析典型的.ini文件。

考虑使用库代码而不是自己编辑。

例如, Zend_Config 处理此类事情很好。

我真的很喜欢JasonWolf对此的回答。

关于可能的错误:是的,但是他提供了一个好主意,现在由读者做出防弹。

我的需求更基本:从分隔列表中创建一个MD数组。我略微修改了他的代码给我这个。这个版本将为您提供一个带或不带定义字符串的数组,甚至是没有分隔符的字符串。

我希望有人可以做得更好。

$parts = "config.debug.router.strictMode";

$parts = explode(".", $parts);

$value = null;

while($parts) {
  $value = array(array_pop($parts) => $value);
}


print_r($value);
// The attribute to the right of the equals sign
$rightOfEquals = true; 

$leftOfEquals = "config.debug.router.strictMode";

// Array of identifiers
$identifiers = explode(".", $leftOfEquals);

// How many 'identifiers' we have
$numIdentifiers = count($identifiers);


// Iterate through each identifier backwards
// We do this backwards because we want the "innermost" array element
// to be defined first.
for ($i = ($numIdentifiers - 1); $i  >=0; $i--)
{

   // If we are looking at the "last" identifier, then we know what its
   // value is. It is the thing directly to the right of the equals sign.
   if ($i == ($numIdentifiers - 1)) 
   {   
      $a = array($identifiers[$i] => $rightOfEquals);
   }   
   // Otherwise, we recursively append our new attribute to the beginning of the array.
   else
   {   
      $a = array($identifiers[$i] => $a);
   }   

}

print_r($a);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top