У меня есть список команд в 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