2017-04-11 9 views
2

임 배열과 키의 경로 지정, 중첩 배열 (배열을 포함하는 배열을 포함하는 배열 ...) 나는 마지막 값을 얻을 필요가액세스 중첩 배열은

에 액세스하려고합니다.

을 감안할 때 foo는 내가 얻을 필요가 ... Z

foo[a][b][c]…[x][y][z] 

임 이보다 더 우아한 방법이 있는지 궁금?

function getValueRecursive(array $array, string ...$identifyer){ 
    $value = $array; 

    foreach($identifyer as $key){ 
     if(!key_exists($key, $value)) 
      return NULL; 

     $value = $value[$key]; 
    } 

    return $value; 
} 

$foo = [ 
    'a' => [ 
     'b' => [ 
      'c' => "Hallo Welt!" 
     ] 
    ] 
]; 

echo getValueRecursive($foo, 'a', 'b', 'c');         // Returns "Hallo Welt!" 
+0

예상 하시겠습니까? 나는 내 게시물에 업데이 트했습니다. –

답변

3

PHP code demo

<?php 

$foo = [ 
    'a' => [ 
     'b' => [ 
      'c' => "Hallo Welt!" 
     ] 
    ] 
]; 
$result=array(); 
array_walk_recursive($foo, function($value,$key) use (&$result){ 
    $result[]=$value; 
}); 
print_r($result[0]); 

또는

<?php 
ini_set("display_errors", 1); 
$foo = [ 
    'a' => [ 
     'b' => [ 
      'c' => "Hallo Welt!" 
     ] 
    ] 
]; 
echo getValueOfArray($foo,"a","b","c"); 
function getValueOfArray($array) 
{ 
    $args=func_get_args(); 
    unset($args[0]); 
    $string=""; 
    foreach($args as $value) 
    { 
     $string.="['$value']"; 
    } 
    eval('if(isset($array'.$string.')) 
    { 
     $result= $array'.$string.'; 
    }'); 
    return $result; 
} 

출력 : Hallo Welt!

+0

이전 버전보다 훨씬 정확하고 정확합니다. 당신은 그가 수행하고있는 것 대신에 그와 같은 것을 할 수 있다고 말할 수 있습니다. –

+0

@AlivetoDie 나는 모두가 downvoting하는 것을 알지 못합니다. 심지어 누군가를 도우려고 응답하려고합니다. –

+0

-ve 마킹에서 호의적이지 않습니다. 너의 일을해라. 여기있는 사람들은 정신 나간 사람입니다 (아무런 이유없이 마킹을하는 사람들). 처음 예제에 대한 BTW +1 –

1

일부 시간 AG o ArrayAccess 인터페이스를 사용하여 이러한 작업을 수행하는 arrays library을 작성했습니다. 값을 검색 할뿐만 아니라 값을 저장하고 삭제할 수 있습니다.

public function offsetGet($offset) 
    { 
     $this->setOffsets($offset); 
     return $this->walkThroughOffsets(
      $this->container, 
      function ($array, $offset) { 
       return $array[$offset]; 
      }, 
      $this->undefinedOffsetAction 
     ); 
    } 
:이 같은 offsetGet 방법을 (당신이 배열 값에 액세스하려고 할 때 호출되는) 구현할 수있는이 방법을 갖는

protected function walkThroughOffsets(
     &$array, 
     Callable $baseCaseAction, 
     Callable $offsetNotExistsAction 
    ) { 
     $offset = array_shift($this->offsets); 
     if (is_scalar($offset) && isset($array[$offset])) { 
      if (empty($this->offsets)) { 
       return $baseCaseAction($array, $offset); 
      } 
      return $this->walkThroughOffsets(
       $array[$offset], 
       $baseCaseAction, 
       $offsetNotExistsAction 
      ); 
     } 
     return $offsetNotExistsAction($array, $offset); 
    } 

: 모든 offset*() 방법에 대한

내가 고차 방법 walkThroughOffsets을 사용

그러면 일반적인 배열처럼 간단하게 값을 얻을 수 있습니다.

$array = new CompositeKeyArray([ 
    'foo' => [ 
     'bar' => 'baz' 
    ] 
]); 

var_dump($array[['foo', 'bar']]); // => string(3) "baz" 
var_dump($array[['foo', 'quux']]); // => PHP Fatal error: Uncaught UndefinedOffsetException: Undefined offset quux.