2012-01-12 3 views
0

나는 csv 파일에 명령 목록이 있습니다동적 다차원 배열에 깊이 새 항목을 추가

[Parent Full Command ; Command; Command Description] 
;show;Show some info 
;configure;Configure the equipment 
show;conf;display the conf 
show;port;display ports informations 
show port;interface;Display port interface description 
configure;interface;Configure the interface 
.... 

나는 전체를 만들기 위해, JSON 객체로이 파일을 구문 분석하고 싶습니다 명령 트리를 열고 내 MongoDB에 저장하십시오. 예 : 사실

{ 
    'show':{ 
    'desc': "Display Ports informations", 
    'child': [ 
     'port':{ 
       'desc': "Display Ports informations", 
       'child':[ 
         'interface':{ 
          'desc':"Display port interface information" }, 
         'description':{ 
          'desc':"Display port interface description" } 
         ] 
     }, 
     'conf':{...}, 
     ] 

    } 
} 

, 내 스크립트가 작동하지만 일부 정적 논리을 썼다 나는 개선 싶습니다

<?php 
function parsefile($file){ 
     $fichier_lu = file($file); 

     $json = array(); 
     foreach ($fichier_lu as $numero_ligne => $t) { 
      $j = array(); 

      $T = explode(";",$t); 

      $command_m = $T[0]; 
      $command = $T[1]; 
      $description = @preg_replace('/\r\n/','',$T[2]); 

      if($command_m != "") $com = $command_m." ".$command; 
      else $com = $command; 

      $j = array(
      'command'=>$com, 
      'description' => $description 
     ); 

      $parents = explode(" ",$T[0]); 
      $age = sizeof($parents); 


      if($age > 1){ 
       //It sucks down here.... 
       switch($age){ 
        case 2: $json[$parents[0]]['child'][$command] = $j; break; 
        case 3: $json[$parents[0]]['child'][$parents[1]]['child'][$command] = $j; break; 
        case 4: $json[$parents[0]]['child'][$parents[1]]['child'][$parents[2]]['child'][$command] = $j; break; 
        ...... 
        .......... 
        .............. 
        default: break; 
       } 

      } else { 
       $json[$command] = $j; 
      } 
     } 
     return json_encode($json); 
    } 
?> 

당신이 볼 수 있듯이, 나는 몇 가지 문제가있을 때 I 자식의 자식에게 몇 가지 요소를 추가해야합니다.

mother 명령에 새 하위 요소를 동적으로 추가하고 "switch/case"문을 삭제하려면 어떻게해야합니까?

팁 주셔서 감사합니다. 참고로 현재 행에 대한 목표를 설정하여 깊은 배열의 올바른 위치를 대상으로

답변

2

이 훨씬 쉬워집니다 :

function parsefile($file,$delimiter=';',$skip_header=1){ 
    $handle = fopen($file,'r'); 
    $skip_header = max(0,intval($skip_header)); 
    while($skip_header > 0){ 
     fgets($handle); 
     $skip_header--; 
    } 
    $return = array(); 
    while($data = fgetcsv($handle,0,$delimiter)){ 
     $command_list = array_filter(explode(' ',$data[0])); 
     $target = &$return; 
     if(!empty($command_list)){ 
      foreach($command_list as $command){ 
      if(!isset($target[$command])) $target[$command] = array(); 
      if(!isset($target[$command]['child'])) $target[$command]['child'] = array();    
      $target = &$target[$command]['child']; 
      } 
     } 
     $target[$data[1]] = array('desc' => $data[2]); 
     unset($target); 
    } 
    return json_encode($return); 
} 
+0

감사합니다! 완벽하게 작동합니다! – Franquis