从JSON在PHP中填充下拉菜单 [英] Populate Dropdown Menu in PHP from JSON
本文介绍了从JSON在PHP中填充下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在文件menu.txt
中具有以下JSON:
I have the following JSON in a file menu.txt
:
[{
"title":"About",
"url":"/about",
"nodes":[
{"title":"Staff","url":"/about/staff"},
{"title":"Location","url":"/about/location"}
]},{
"title":"Contact",
"url":"/contact"
}]
使用以下Javascript:
Using the following Javascript:
var menu = // JSON from menu.txt
function parseNodes(nodes) {
var ul = document.createElement('UL');
for(var i=0; i < nodes.length; i++) {
ul.appendChild(parseNode(nodes[i]));
}
return ul;
}
function parseNode(node) { // takes a node object and turns it into a <li>
var li = document.createElement('LI');
var a = ('<a href="'+node.url+'">'+node.title+'</a>');
li.innerHTML = a;
if(node.nodes) li.appendChild(parseNodes(node.nodes));
return li;
}
document.getElementById('menu').appendChild(parseNodes(menu));
我可以创建以下HTML:
I can create the following HTML:
<div id="menu">
<ul>
<li><a href="/about">About</a></li>
<ul>
<li><a href="/about/staff">Staff</a></li>
<li><a href="/about/location">Location</a></li>
</ul>
</li>
<li><a href="/contact">Contact</a></li>
</ul>
</div>
有没有一种简便的方法可以在PHP中做到这一点,以使其对搜索引擎更加友好?最好是我可以在页面中包含menu.php
的PHP脚本?
Is there an easy way to do this in PHP as to be more search-engine friendly? Preferably a PHP script that I could include menu.php
in my pages?
<?php
$file = "menu.txt";
$json = json_decode(file_get_contents($file), true);
// ????
?>
推荐答案
这应该使您入门;)
<?php
function parseNodes($nodes) {
$ul = "<ul>\n";
foreach ($nodes as $node) {
$ul .= parseNode($node);
}
$ul .= "</ul>\n";
return $ul;
}
function parseNode($node) {
$li = "\t<li>";
$li .= '<a href="'.$node->url.'">'.$node->title.'</a>';
if (isset($node->nodes)) $li .= parseNodes($node->nodes);
$li .= "</li>\n";
return $li;
}
$json = '[{
"title":"About",
"url":"/about",
"nodes":[
{"title":"Staff","url":"/about/staff"},
{"title":"Location","url":"/about/location"}
]},{
"title":"Contact",
"url":"/contact"
}]';
$nodes = json_decode($json);
$html = parseNodes($nodes);
echo $html;
这篇关于从JSON在PHP中填充下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文