我在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”语句?
感谢您的提示!
答案 0 :(得分: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);
}