문제

부분이 문자열에 의해 결정되는 다차원 배열을 만들려고합니다. 사용 중입니다 . 구분 기자로서, 각 부분 (마지막 부분 제외)은 배열이어야합니다.
전:

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

오류 확인이 있도록 확실히 다시 작성하십시오.

검보의 대답은 좋아 보인다.

그러나 일반적인 .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