j6m*_*mes 2 php arrays recursion build multidimensional-array
我从MySQL数据库返回一个页面列表及其父页面,并将所有结果放入一个数组中,如下所示,每个结果都是一个数组,其中包含论坛的父级,名称和ID(数组页面的键也是与页面ID相同).
为了模型和应用,还有一些其他参数.
所以,MySQL查询将返回此数据集.
pages=>
[1] => array(id=>1,
parent=>0,
name=>Hello World)
[2] => array(id=>1,
parent=>1,
name=>Child of Hello World)
[3] => array(id=>1,
parent=>0,
name=>Brother of Hello World)
[4] => array(id=>4,
parent=>2,
name=Grand-child of Hello World)
[6] => array(id=>6,
parent=>4,
name=Great-grand-child of Hello World)
Run Code Online (Sandbox Code Playgroud)
然后我想将数组转换成看起来像这样的东西
pages=>
[1] => id=>1,
name=>Hello World
children=>
[2] => id=>1
name=>Child of Hello World
children=>
[4] =>
id=>4
name=> Grand-child of Hello World)
children=>
[6] =>
id=>6
name=> Great-grand-child of Hello World
children= null
[3] => array(id=>1,
name=>Brother of Hello World
children=>null
Run Code Online (Sandbox Code Playgroud)
基本上,我想将线性数组转换为嵌套的多维数组,以便我可以打印我的站点地图.
它需要是一个递归的解决方案.有超过700页,最多5或6个级别.
我只想做1个mysql查询.不是700所以请不要给我一个基于mysql的解决方案.
<?php
$pages = array();
$pages[1] = array('id' => 1, 'parent' => 0, 'name' => 'Hello World');
$pages[2] = array('id' => 1, 'parent' => 1, 'name' => 'Child of Hello World');
$pages[3] = array('id' => 1, 'parent' => 0, 'name' => 'Brother of Hello World');
$pages[4] = array('id' => 4, 'parent' => 2, 'name' => 'Grand-child of Hello World');
$pages[6] = array('id' => 6, 'parent' => 4, 'name' => 'Great-grand-child of Hello World');
$children = array();
foreach($pages as $key => $page){
$parent = (int)$page['parent'];
if(!isset($children[$parent]))
$children[$parent] = array();
$children[$parent][$key] = array('id' => $page['id'], 'name' => $page['name']);
}
$new_pages = recursive_append_children($children[0], $children);
function recursive_append_children($arr, $children){
foreach($arr as $key => $page)
if(isset($children[$key]))
$arr[$key]['children'] = recursive_append_children($children[$key], $children);
return $arr;
}
print_r($new_pages);
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Array
(
[1] => Array
(
[id] => 1
[name] => Hello World
[children] => Array
(
[2] => Array
(
[id] => 1
[name] => Child of Hello World
[children] => Array
(
[4] => Array
(
[id] => 4
[name] => Grand-child of Hello World
[children] => Array
(
[6] => Array
(
[id] => 6
[name] => Great-grand-child of Hello World
)
)
)
)
)
)
)
[3] => Array
(
[id] => 1
[name] => Brother of Hello World
)
)
Run Code Online (Sandbox Code Playgroud)
这是一个构建树的快速递归函数.请注意,它并不是很好(一个原因是因为它没有删除已经添加到树中的项目,所以每次递归它都会通过整个列表) - 但它应该足以让你开始.
function buildTree($itemList, $parentId) {
// return an array of items with parent = $parentId
$result = array();
foreach ($itemList as $item) {
if ($item['parent'] == $parentId) {
$newItem = $item;
$newItem['children'] = buildTree($itemList, $newItem['id']);
$result[] = $newItem;
}
}
if (count($result) > 0) return $result;
return null;
}
$myTree = buildTree($myArray, 0);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8886 次 |
| 最近记录: |