我正在创建一个树状结构菜单,就像wordpress一样。我能够像wordpress一样做。我的UI看起来像这样:
在这里,用户可以添加他们需要的子菜单数量。 下面的JSON代码格式:
[
{
"layout":0,
"layouttype":1,
"deleted":0,
"new":0,
"deleter":0,
"slug":"Home",
"name":"Home",
"id":"12122017033717-1"
},
{
"layout":0,
"layouttype":4,
"deleted":0,
"new":0,
"deleter":0,
"slug":"About",
"name":"About",
"id":"12122017033717-2"
},
{
"layout":0,
"layouttype":1,
"deleted":0,
"new":0,
"deleter":0,
"slug":"Services",
"name":"Servicessss",
"id":"12122017033717-3",
"children":[
{
"layout":0,
"layouttype":6,
"deleted":0,
"new":0,
"deleter":1,
"slug":"Services-1",
"name":"Services 1",
"id":"12122017033717-4"
},
{
"layout":0,
"layouttype":1,
"deleted":0,
"new":0,
"deleter":1,
"slug":"ss",
"name":"ss",
"id":"12122017033920-1",
"children":[
{
"layout":0,
"layouttype":1,
"deleted":0,
"new":0,
"deleter":1,
"slug":"fddzfsdz",
"name":"fddzfsdz",
"id":"12122017040829-1"
},
{
"layout":0,
"layouttype":3,
"deleted":0,
"new":0,
"deleter":1,
"slug":"fddzfsdzfcg",
"name":"Sarath",
"id":"12122017040829-2"
},
{
"layout":0,
"layouttype":1,
"deleted":0,
"new":0,
"deleter":1,
"slug":"asassssss",
"name":"asassssss",
"id":"12122017041219-1"
}
]
}
]
}
]
获取和更新一个子菜单的当前代码来了。
$arr = json_decode($arr);
foreach($arr as $item) {
$menuid = $item - > id;
if ($menuid == $id) {
$item - > layouttype = $page_layout;
}
if (property_exists($item, 'children')) {
foreach($item - > children as $innerRow) {
$submenuid = $innerRow - > id;
if ($submenuid == $id) {
$innerRow - > layouttype = $page_layout;
}
}
}
}
我需要编辑数据' layouttype'动态。我尝试使用foreach()
并且它可以正常运行子菜单的一个或两个子菜单,但如果用户添加了更多子菜单,则代码将无法容纳。
那么有人可以告诉我这个foreach循环可以修改的最佳方式,以便它根据子菜单子的数量来运作吗?
答案 0 :(得分:0)
如果您想要无限期/无限嵌套,则需要使用循环函数。
E.g。 (伪代码)
function recurrentMenuProcess(branch) {
foreach (item in branch) {
//processing here
if (item.hasChildren) {
recurrentMenuProcess(item);
}
}
}
recurrentMenuProcess(json);