我想从网址地址创建一个导航,以便它们通过网址正确地相互嵌套。
- 我有一个 URL 地址数组及其 ID:
array(
[0] => array(
[id] => 1,
[url] => "/admin/pages"
),
[1] => array(
[id] => 2,
[url] => "/admin/store"
),
[2] => array(
[id] => 3,
[url] => "/admin/store/products"
)
)
- 结果应如下所示,以便我可以创建
<ul></ul>
导航:
[admin] => array(
[pages] => 1,
[store] => array(
[products] => 3
)
)
有人可以帮助我吗?
我已经编写了一个php脚本来直接匹配上述要求。但是,如果url中有更多部分,请根据需要进行更改。
$array = array(
0 => array(
'id' => 1,
'url' => "/admin/pages"
),
1 => array(
'id' => 2,
'url' => "/admin/store"
),
2 => array(
'id' => 3,
'url' => "/admin/store/products"
)
);
$out = [];
foreach ($array as $key => $arr) {
$parts = array_filter(explode("/", $arr['url']));
$first = array_shift($parts);
$last = array_pop($parts);
if (count($parts) > 0 && isset($out[$first][end($parts)])) {
$out[$first][end($parts)] = [$last => $arr['id']];
} else {
$out[$first][$last] = $arr['id'];
}
}
var_dump($out);