2014-10-23 2 views
0

약간의 문제가 있습니다. 다음은 배열입니다.키 경로로 배열 값 가져 오기 PHP

$data = array(
    'properties'=>array{ 
     [0]=> 
      array { 
       ["name"]=>"prop1", 
       ["properties"]=> 
       array { 
        [0]=> 
         array(5) { 
          ["name"]=>"sub_prop1" 
         } 
        [1]=> 
         array(6) { 
          ["name"]=>"sub_prop2", 
          ["properties"]=> 
          array(2) { 
            [0]=> 
            array(6) { 
              ["name"]=>"MARK" 
            } 
          } 
         } 
       } 
     }, 
     [1]=> 
      array { 
       ["name"]=>"prop2" 
      } 
    } 
); 

배열 경로는 0/1/0입니다. 이름이 "Mark"인 배열까지 모든 키를 알고 있습니다.이 배열을 이와 동등하게 만들기 위해 재귀 함수가 필요합니다 : $ data [ 'properties'] [0] [ 'properties] [1] [properties] [0 ]. 제발 도와주세요 !!!

답변

1

나는 재귀 대신에 참조를 사용할 것이지만, 누군가는 재귀 함수로 대답 할 것이다. name 키를 알고 있으면 경로에 넣으십시오. 하지 않으면 것은 다음 reset은 첫 번째 항목을 얻을 것이다 :

$path = array('properties', 0, 'properties', 1, 'properties', 0); 

$result =& $data; 

foreach($path as $key) { 
    $result =& $result[$key]; 
} 
echo reset($result); 

// or if you want array('name' => 'MARK') 
print_r($result); 
1

그리고 @blckwngd하여이 situasion에 대한 재귀 함수를,하지만 난 @의 AbraCadaver의 솔루션처럼 :

function get_array_by_key_path($data, $key_path){ 
    if(count($key_path) == 0){ 
     return $data;   
    } 
    $key = array_shift($path_keys); 
    // and recursion now 
    return get_array_by_key_path($data['properties'][$key], $keys); 
}