我有一个包含以下内容的JSON文件:
"Menus": [{
"MenuId": "1",
"MenuName": "Perencanaan dan Pengadaan",
"MenuParent": "",
"MenuLink": ""
}, {
"MenuId": "1-1",
"MenuName": "RKA / DPA",
"MenuParent": "1",
"MenuLink": ""
}, {
"MenuId": "1-1-1",
"MenuName": "Daftar RKA / DPA",
"MenuParent": "1-1",
"MenuLink": "rkbu"
},
我想动态地将这些数据放入无序列表中。所以我想要的输出是这样的(有3级列表):
Perencanaan dan Pengadaan
RKA / DPA
Daftar RKA / DPA
我试过这段代码:
echo "<ul>";
foreach($get_data['Menus'] as $node){
if(strlen($node['MenuId']) == 1){
echo "<li>" . $node['MenuName'];
echo "</li>";
}
echo "<ul>";
if(strlen($node['MenuId']) == 3){
echo "<li>".$node['MenuName']."</li>";
}
if(strlen($node['MenuId']) == 5){
echo "<ul>";
echo "<li>".$node['MenuName']."</li>";
echo "</ul>";
}
echo "</ul>";
}
echo "</ul>";
但我发现它不是动态的,因为它取决于字符串长度。我读过最好的方法是使用递归方法。但我找不到我的JSON文件的递归模式。任何人都可以帮我找到解决方案吗?感谢
答案 0 :(得分:1)
我认为不可能直接在平面JSON数据上进行递归调用。
我建议您先将平面数据转换为多维数组,然后递归生成菜单。
我从这里获取了部分代码:Dynamically creating/inserting into an associative array in PHP
$get_data = array(
array(
"MenuId" => "1",
"MenuName" => "Perencanaan dan Pengadaan",
"MenuParent" => "",
"MenuLink" => ""
),
array(
"MenuId" => "1-1",
"MenuName" => "RKA / DPA",
"MenuParent" => "1",
"MenuLink" => ""
),
array(
"MenuId" => "1-1-1",
"MenuName" => "Daftar RKA / DPA",
"MenuParent" => "1-1",
"MenuLink" => "rkbu"
)
);
function insert_into(&$array, array $keys, $value) {
$last = array_pop($keys);
foreach($keys as $key) {
if(!array_key_exists($key, $array) ||
array_key_exists($key, $array) && !is_array($array[$key])) {
$array[$key]['items'] = array();
}
$array = &$array[$key]['items'];
}
$array[$last]['value'] = $value;
}
function create_menu($menuItems) {
$content = '<ul>';
foreach($menuItems as $item) {
$content .= '<li>' . $item['value'];
if(isset($item['items']) && count($item['items'])) {
$content .= create_menu($item['items']);
}
$content .= '</li>';
}
$content .= '</ul>';
return $content;
}
$menuItems = array();
foreach($get_data as $item) {
$levels = explode('-', $item['MenuId']);
insert_into($menuItems, $levels, $item['MenuName']);
}
print_r($menuItems);
print create_menu($menuItems);
输出:
Array (
[1] => Array (
[value] => Perencanaan dan Pengadaan
[items] => Array (
[1] => Array (
[value] => RKA / DPA
[items] => Array (
[1] => Array (
[value] => Daftar RKA / DPA
)
)
)
)
)
)
<ul>
<li>Perencanaan dan Pengadaan
<ul>
<li>RKA / DPA
<ul>
<li>Daftar RKA / DPA</li>
</ul>
</li>
</ul>
</li>
</ul>