0

질문이 있습니다. PHP에서 다차원 배열을 동적으로 생성하는 가장 쉬운 방법은 무엇입니까? 여기php 다중 배열을 동적으로 생성합니다.

정적 버전 :

$tab['k1']['k2']['k3'] = 'value'; 

내가()
내가 변수 변수 ($$) 성공적인 아니에요 평가를 피하기 위해 싶습니다
그래서 함수의 재미를 개발하기 위해 노력하고있어 그러한 인터페이스 :

$tab = fun($tab, array('k1', 'k2', 'k3'), 'value'); 

해결책이 있습니까? 가장 간단한 방법은 무엇입니까?

관련, 애니

+0

모든 솔루션에 대해 감사드립니다. 다른 간단한 코드는 다음과 같습니다 (function setValueFromPath) : http://stackoverflow.com/questions/7850744/how-to-reffer-dynamically-to-a-php-array-variables –

답변

1

여기에는 여러 가지 방법이 있지만 여기에는 N 개의 인수를 함수에 전달하는 PHP의 기능을 사용하는 방법이 있습니다. 이렇게하면 3, 2 또는 7 등의 깊이를 가진 배열을 만들 수 있습니다.

$array = MakeMultiArray('value', 'k1', 'k2', 'k3'); 

을 그리고이를 생성합니다 : 여기

// pass $value as first param -- params 2 - N define the multi array 
function MakeMultiArray() 
{ 
    $args = func_get_args(); 
    $output = array(); 
    if (count($args) == 1) 
     $output[] = $args[0]; // just the value 
    else if (count($args) > 1) 
    { 
     $output = $args[0]; 
     // loop the args from the end to the front to make the array 
     for ($i = count($args)-1; $i >= 1; $i--) 
     { 
      $output = array($args[$i] => $output); 
     } 
    } 
    return $output; 
} 

는 그것이 작동 할 방법

Array 
(
    [k1] => Array 
     (
      [k2] => Array 
       (
        [k3] => value 
       ) 
     ) 
) 
0

$ 탭은 항상 3 개 인덱스가있는 경우이 작업을해야합니다 :

기능 FUNC (& $ 이름, $ 지수, $ 값) { $ 이름 [$ 인덱스를 [0]] [$ indices [1]] [$ indices [2]] = $ value; };

func ($ tab, array ('k1', 'k2', 'k3'), 'value');

1

에 따라 기능 키의 수를 작동합니다.

function fun($keys, $value) { 

    // If not keys array found then return false 
    if (empty($keys)) return false; 

    // If only one key then 
    if (count($keys) == 1) { 
     $result[$keys[0]] = $value; 
     return $result; 
    } 

    // prepare initial array with first key 
    $result[array_shift($keys)] = ''; 

    // now $keys = ['key2', 'key3'] 
    // get last key of array 
    $last_key = end($keys); 

    foreach($keys as $key) { 
     $val = $key == $last_key ? $value : ''; 
     array_walk_recursive($result, function(&$item, $k) use ($key, $val) { 
      $item[$key] = $val; 
     }); 
    } 
    return $result; 
} 
관련 문제