Парсинг json данных с конфигурации, php json
Входные данные:
config = 3
config_b.items = item1
config_b.items = item2
config_b.items.named_item = 123
config_c.root.a.b.c = 13
Как в итоге должно быть:
{"config":3,
"config_b": {
"items":{
"0":"item1",
"1":"item2",
"named_item":123
}
}, "config_c": {
"root": {
"a": {
"c":13
}
}
}
}
Это то, что получилось у меня:
$input = '
config = 3
config_b.items = item1
config_b.items = item2
config_b.items.named_item = 123
config_c.root.a.b.c = 13';
$output = [];
$back_slash_exploded = explode("\n", $input);
foreach ($back_slash_exploded as $item) {
if ($item) {
$exploded = explode(' = ', $item);
$dot_exploded = explode('.', $exploded[0]);
$output[$dot_exploded[0]] = [];
foreach ($dot_exploded as $new_key) {
create_array($output, $new_key, $dot_exploded[0]);
}
}
}
function create_array(&$output, $new_key, $prev_key) {
if (!isset($output[$new_key])) {
foreach ($output as $key => $value) {
if ($key == $prev_key) {
$output[$prev_key][$new_key] = [];
} else {
create_array($output[$key], $new_key, $prev_key);
}
}
}
}
var_dump($output);
array(3) {
["config"]=>
array(0) {
}
["config_b"]=>
array(2) {
["items"]=>
array(0) {
}
["named_item"]=>
array(0) {
}
}
["config_c"]=>
array(4) {
["root"]=>
array(0) {
}
["a"]=>
array(0) {
}
["b"]=>
array(0) {
}
["c"]=>
array(0) {
}
}
}