我将数据1保留得很深(也许保留在数据库中)
$data = [
"games" => "",
"games>sport" => "",
"games>sport>enabled" => true,
"feature" => "",
"feature>register" => "",
"feature>register>enabled" => true,
"contact" => "",
"contact>tel" => "",
"contact>tel>lang" => "th",
"contact>tel>number" => "012345678"
];
然后转换为json
结果:
{
"games": {
"sport":
"enabled": true
}
},
"feature": {
"register": {
"enabled": true,
"captcha": true
}
},
"contact": {
"tel": {
"lang": "th",
"number": "012345678"
}
}
编辑:将其标记为与事件未关闭的文章重复的人。我必须找到路
这是我自己的答案。
$col = [];
foreach($data as $key => $val) {
$ex = explode(">", $key);
$cnt = count($ex);
if (count($ex) > 5) { die('Maximum deep is 5'); }
if ($cnt == 1) { $col[$ex[0]] = $val; }
if ($cnt == 2) { $col[$ex[0]][$ex[1]] = $val; }
if ($cnt == 3) { $col[$ex[0]][$ex[1]][$ex[2]] = $val; }
if ($cnt == 4) { $col[$ex[0]][$ex[1]][$ex[2]][$ex[3]] = $val; }
if ($cnt == 5) { $col[$ex[0]][$ex[1]][$ex[2]][$ex[3]][$ex[4]] = $val; }
}
die(json_encode($col));