Pregunta

Estoy tratando de crear una matriz multidimensional cuyas partes están determinadas por una cadena. Estoy usando . como delimitador, y cada parte (excepto la última) debería ser una matriz
ex:

config.debug.router.strictMode = true

Quiero los mismos resultados que si tuviera que escribir:

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

Este problema realmente me puso en círculos, cualquier ayuda es apreciada. Gracias!

¿Fue útil?

Solución

Supongamos que ya tenemos la clave y el valor en $ key y $ val , entonces puede hacer esto:

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

Construir la matriz de izquierda a derecha:

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

Y de derecha a izquierda:

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

Otros consejos

Digo dividir todo, comenzar con el valor y trabajar hacia atrás desde allí, cada vez, envolviendo lo que tienes dentro de otra matriz. Me gusta así:

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

Definitivamente reescríbalo para que tenga una comprobación de errores.

La respuesta de Gumbo se ve bien.

Sin embargo, parece que desea analizar un archivo .ini típico.

Considere usar el código de la biblioteca en lugar de usar el suyo.

Por ejemplo, Zend_Config maneja este tipo de las cosas muy bien.

Realmente me gusta la respuesta de JasonWolf a esto.

En cuanto a los posibles errores: sí, pero proporcionó una gran idea, ahora depende del lector hacer que sea a prueba de balas.

Mi necesidad era un poco más básica: desde una lista delimitada, crear una matriz de MD. Modifiqué ligeramente su código para darme eso. Esta versión le dará una matriz con o sin una cadena definida o incluso una cadena sin el delimitador.

Espero que alguien pueda hacer esto aún mejor.

$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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top