我有以下代碼:
$indexes = [
['id' => 1, 'parentid' => 0, 'route' => 'root', 'title' => 'root'],
['id' => 2, 'parentid' => 1, 'route' => 'parent', 'title' => 'parent'],
['id' => 3, 'parentid' => 2, 'route' => 'child', 'title' => 'child']
];
$parentid = 1;
$indexes = buildSubs($indexes, $parentid);
var_dump($indexes);
function buildSubs(array $elms, int $parentId = 0)
{
$branch = [];
foreach ($elms as $elm) {
if ($elm['parentid'] == $parentId) {
$children = buildSubs($elms, $elm['id']);
if ($children) {
$elms['pages'] = $children;
}
$branch[] = $elm;
}
}
return $branch;
}
我想以這種格式結束一個陣列:
$index=[
[
'id'=>1,
'pages' => [
[
'id'=>2,
'pages' => [
[
'id'=>3
]
]
];
其中子路由被封裝到pages第 2 個陣列中的一個陣列中,其中 2 為id2,而id2pages位于id1 中的陣列中。
似乎沒有按預期作業,并且無法弄清楚。
uj5u.com熱心網友回復:
您的代碼按預期作業,您只是使用了整個陣列$elms而不是$elm. 此外,如果您想要整個樹/路線,您需要從$parentId0開始。然后使用您的代碼和更改后的變數名稱和父 ID,您將獲得結果陣列:
Array
(
[0] => Array
(
[id] => 1
[parentid] => 0
[route] => root
[title] => root
[pages] => Array
(
[0] => Array
(
[id] => 2
[parentid] => 1
[route] => parent
[title] => parent
[pages] => Array
(
[0] => Array
(
[id] => 3
[parentid] => 2
[route] => child
[title] => child
)
)
)
)
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/334075.html
