我有多个json文件,我需要将它们全部加入以收集以创建我的动态菜单。
这是当前的输出
{
"Dashboard": {
"parent": "Dashboard",
"url": "#\/dashboard",
"submenu": []
},
"HRM": {
"submenu": [
{
"title": "Holiday",
"url": "#\/holidays"
},
{
"divider": "true"
},
{
"header": "Header 2"
},
{
"title": "Again...a link.",
"url": "errrr"
}
]
} }
这是所需的输出
{
"parent": "Dashboard",
"url": "#\/dashboard",
"submenu": []
}, {
"parent": "HRM",
"submenu": [{
"title": "Holiday",
"url": "#\/holidays"
}, {
"divider": "true"
}, {
"header": "Header 2"
}, {
"title": "Again...a link.",
"url": "errrr"
}, {
"header": "Holiday"
},
{
"title": "list",
"url": ""
},
{
"title": "test",
"url": ""
}]
}
这是我的PHP代码
$files = \File::allFiles($directory);
foreach ($files as $file)
{
if (preg_match("/config.json/i", $file) && \File::size($file) >0) {
$menu =json_decode(\File::get($file), TRUE)['menu'];
// $menu = $menu['menu'];
$id = $menu['parent'];
if(!empty($menu['submenu'])){
$result[$id]['submenu'] = $menu['submenu'];
}else{
$result[$id] = $menu;
}
}
}
JSON文件1示例
{
"menu": {
"parent": "Dashboard",
"url": "#/dashboard",
"submenu": [
]
}
}
JSON文件2示例
{
"menu": {
"parent": "HRM",
"submenu": [
{
"title": "Holiday",
"url": "#/holidays"
},
{
"divider": "true"
},
{
"header": "Header 2"
},
{
"title": "Again...a link.",
"url": "errrr"
}
]
}
}
JSON文件3示例
{
"menu": {
"parent": "HRM",
"submenu": [
{
"header": "Holiday"
},
{
"title": "list",
"url": ""
},
{
"title": "test",
"url": ""
}
]
}
}
答案 0 :(得分:1)
我对您的代码进行了一些更改,
$files = \File::allFiles($directory);
$result = array();
foreach ($files as $file)
{
if (preg_match("/config.json/i", $file) && \File::size($file) >0) {
$parent = $menu['parent'];
//checker is used to see if document is already added under an existing parent id
$checker = true;
foreach($result as $key=>$value){
if(is_array($value) && $value["parent"]==$parent){
$checker = false;
//merging the submenus of equal parent ids
$submenuSet = array();
if(!empty($value["submenu"]) && is_array($value["submenu"])){
foreach($value["submenu"] as $value1){
$submenuSet[] = $value1;
}
}
if(!empty($menu["submenu"]) && is_array($menu["submenu"])){
foreach($menu["submenu"] as $value2){
$submenuSet[] = $value2;
}
}
$value["submenu"] = $submenuSet;
}
$result[$key] = $value;
}
//if a new parent id add it to results
if($checker){
$result[] = $menu;
}
}
}
输出就像这样,
[
{
"parent": "Dashboard",
"url": "#\/dashboard",
"submenu": [
]
},
{
"parent": "HRM",
"submenu": [
{
"title": "Holiday",
"url": "#\/holidays"
},
{
"divider": "true"
},
{
"header": "Header 2"
},
{
"title": "Again...a link.",
"url": "errrr"
},
{
"header": "Holiday"
},
{
"title": "list",
"url": ""
},
{
"title": "test",
"url": ""
}
]
}
]