2012-01-12 63 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); 
    } 
?> 

正如你所看到的,我有一些問題,當我需要添加一些元素孩子的孩子的孩子,等等。

我怎樣才能動態地添加新的子元素,他們的母親的命令,並刪除「的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 2012-01-12 16:49:46