我有一个像这样的PHP数组。
<?php $pages = array (
'home' => array (
'title' => 'Home Page',
'slug' => 'home-page'
),
'contact' => array (
'title' => 'Contact',
'slug' => 'contact-page'
),
'project' => array (
'title' => 'Project',
'slug' => 'project-page',
'parent' => 'contact'
),
'analytics' => array (
'title' => 'Analytics',
'slug' => 'analytics-page',
'parent' => 'contact'
),
'apps' => array (
'title' => 'Apps',
'slug' => 'apps-page',
'parent' => 'analytics'
)
); ?>
我需要把它转换成一个多维数组的结构。
<?php $pages = array (
'home' => array (
'title' => 'Home Page',
'slug' => 'home-page'
),
'contact' => array (
'title' => 'Contact',
'slug' => 'contact-page',
'children' => array(
'portfolio' => array (
'title' => 'Portfolio',
'slug' => 'portfolio-page',
),
'analytics' => array (
'title' => 'Analytics',
'slug' => 'analytics-page',
'parent' => 'contact',
'children' => array(
'apps' => array (
'title' => 'Apps',
'slug' => 'apps-page',
)
)
)
)
)
); ?>
我试过这段PHP代码,但它只能转换为一维数组。
<?php $formatted_pages = array();
foreach ($pages as $key => $page) {
if ( $page['parent'] ) {
$formatted_pages[ $page['parent'] ]['children'][$key]['title'] = $page['title'];
$formatted_pages[ $page['parent'] ]['children'][$key]['slug'] = $page['slug'];
} else {
$formatted_pages[] = array(
'title' => $page['title'],
'slug' => $page['slug']
);
}
} ?>
我不知道有什么办法可以让它在任何级别上迭代,不管数组是多少级。
试试这个
`$pages = array (
'home' => array (
'title' => 'Home Page',
'slug' => 'home-page'
),
'contact' => array (
'title' => 'Contact',
'slug' => 'contact-page'
),
'project' => array (
'title' => 'Project',
'slug' => 'project-page',
'parent' => 'contact'
),
'analytics' => array (
'title' => 'Analytics',
'slug' => 'analytics-page',
'parent' => 'contact'
),
'apps' => array (
'title' => 'Apps',
'slug' => 'apps-page',
'parent' => 'analytics'
)
);
function makeItTree($pages = [], $parent = null ) {
$roots = [];
$search = [];
foreach ($pages as $alias => $page){
if(($page['parent'] ?? null) === $parent){
$roots[$alias] = $page;
} else {
$search[$alias] = $page;
}
}
foreach ($roots as $alias => &$root){
$children = makeItTree($search, $alias);
if(count($children)){
$root['children'] = $children;
}
}
return $roots;
}
var_dump(makeItTree($pages));`
结果将是这样的
`
array(2) {
["home"]=>
array(2) {
["title"]=>
string(9) "Home Page"
["slug"]=>
string(9) "home-page"
}
["contact"]=>
array(3) {
["title"]=>
string(7) "Contact"
["slug"]=>
string(12) "contact-page"
["children"]=>
array(2) {
["project"]=>
array(3) {
["title"]=>
string(7) "Project"
["slug"]=>
string(12) "project-page"
["parent"]=>
string(7) "contact"
}
["analytics"]=>
array(4) {
["title"]=>
string(9) "Analytics"
["slug"]=>
string(14) "analytics-page"
["parent"]=>
string(7) "contact"
["children"]=>
array(1) {
["apps"]=>
array(3) {
["title"]=>
string(4) "Apps"
["slug"]=>
string(9) "apps-page"
["parent"]=>
string(9) "analytics"
}
}
}
}
}
}
`