[英]How to build a multidimensional nested array in PHP/CodeIgniter?
可以说我有一张桌子,桌子上有记录,代表树的层次结构
id group parent_group_id
--------- ---------- ---------------
1 Parent 1 NULL
2 Parent 2 NULL
3 Parent 3 NULL
4 Child 1 1
5 Child 2 2
6 Child 3 2
7 Child 4 6
我需要构建一个递归函数来构建多维嵌套数组,以便它首先通过构建具有parent_group_ids为NULL的行的顶级数组而从“顶部”开始。 快进几次迭代,我期望最终得到一个像这样的对象
$result = array(
[0] => array(
'id' => 1,
'group' => 'Parent 1',
'parent_group_id' => NULL,
'children' => array(
[0] => array(
'id' => 4,
'group' => 'Child 1'
'parent_group_id' => 1,
'children' => NULL)),
[1] => array(
'id' => 2,
'group' => 'Parent 2',
'parent_group_id' => NULL,
'children' => array(
[0] => array(
'id' => 5,
'group' => 'Child 2'
'parent_group_id' => 2,
'children' => NULL),
[1] => array(
'id' => 6,
'group' => 'Child 3'
'parent_group_id' => 2,
'children' => array(
[0] => array(
'id' => 1,
'group' => 'Child 4'
'parent_group_id' => 6,
'children' => NULL)))
构建这样的东西的最佳方法是什么? 我需要确保它遍历每个“分支”。 我正在猜测何时获取顶级父母的ID,然后继续检查是否存在任何具有parent_group_id等于第一轮运行中每个ID的行。 然后,如果找到子代,则获取这些子代的ID,然后再次检查是否存在子代。 依此类推,直到没有可用的ID进行检查。
我不太熟悉foreach循环来完成类似这样的事情。
看一下这个源代码。
我认为该功能与您要的功能有些相似。
public function getAreaTree(array $elements, $parentId = null) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = getAreaTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return empty($branch) ? null : $branch;
}
您好,我曾在您想要的相同概念上工作。
使用此代码。 对我来说是工作。
function recursion($parent_id = '') {
$categories = array();
$this->db->from('category');
$this->db->where('parent_id', $parent_id);
$result = $this->db->get()->result_array();
if(count($result) > 0) {
foreach ($result as $c) {
$child = $this->recursion($c['category_id']);
if($child) {
$c ['children']= $child;
}
$categories[] = $c;
}
}
return $categories;
}
function get_cat() {
print_r($this->recursion());
}
可以提高预加载所有类别的速度,从而跳过每个新的parent_id的查询。
此函数的作用:加载具有给定parent_id的所有类别,遍历所有这些类别并递归存储在数组中。
但是问题是,这迫使您拥有自己类别的干净树结构。
希望它能帮助您解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.