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