解析JSON导航的更好方法

时间:2018-02-09 19:05:08

标签: php json

我正致力于从JSON创建导航,同时包含顶级和子级别的链接。我希望这可以重复使用多维JSON文件,博客导航,页面等不同深度......

我觉得我的代码有点复杂,并希望能帮助我们简化这一过程。

function generate_navigation($document,$navigation){
$json = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/json/navigation.json'),true);
$parent = $document->createElement('nav');
$i = 0;
function build_segment($document,$node,$data,$name,$i){
    foreach($data as $key => $link){
        if(!is_array($link)){
            $a = $document->createElement('a');
            $a->setAttribute('href',$link);
            if(!is_numeric($key)){
                $link_title = $key;
            } else {
                $link_title = $name;
                $node->setAttribute('class','has-children');
            }
            $a->appendChild($document->createTextNode($link_title));
            $node->appendChild($a);
        } else {
            $nav[$i] = $document->createElement('nav');
            $node->appendChild($nav[$i]);
            build_segment($document,$nav[$i],$link,$key,$i);
            $i++;
        }
    }
}
build_segment($document,$parent,$json[$navigation],null,$i);
return $parent;
}

和JSON

{
"Primary":
    {
        "Home": "/",
        "Blog": "/posts/",
        "Events": "/events/",
        "Places": [
            "/places/",
            {
            "Counties": "/places/counties/",
            "Municipalities": "/places/municipalities/"
            }
        ],
        "Activities": [
            "/activities/",
            {
            "Golf": "/activities/golf/",
            "Disk Golf": "/activities/disc-golf/",
            "Fishing": "/activities/fishing/"
            }
        ],
        "Resources": [
            "/resources/",
            {
            "Public": "/resources/public/",
            "Families": "/resources/families/",
            "Business": "/resources/business/",
            "Hospitals": "/resources/hospitals/"
            }
        ]
    }
}

0 个答案:

没有答案