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”语句?
感谢您的建议!
谢谢!完美的作品! – Franquis 2012-01-12 16:49:46