PHP从列表构建递归数组

标签 php arrays recursion build multidimensional-array

我从 MySQL 数据库返回一个页面列表及其父页面,并将所有结果放入一个数组中,如下所示,其中每个结果都是一个数组,其中包括论坛的父页面、名称和 ID(数组页面的键也与页面 ID 相同)。

为了模型和应用,还有一些其他参数。

  • “根页面”的父页面为 0
  • 没有孤立的页面

因此,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)

然后我想将数组转换成这样的东西

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

基本上,我想将线性数组转换为嵌套的多维数组,以便打印我的站点地图。

它需要是一个递归的解决方案。有 700 多页,多达 5 或 6 个级别。

我只想做 1 个 mysql 查询。不是 700,所以请不要给我基于 mysql 的解决方案。

最佳答案

这是一个构建树的快速递归函数。请注意,它不是很好(一个原因是因为它没有删除已经添加到树中的项目,所以每次递归它都会遍历整个列表) - 但它应该足以让你开始。

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);

关于PHP从列表构建递归数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7046364/

相关文章:

php - PHP中的多个关键字(100s到1000s)搜索(字符串搜索算法)

c++ - std::next_permutation() 来自 vector 的一部分

string - 准备字符串中的重复字符 - 算法

r - R中的尾递归

php - 如何使用 MySQL 查询创建表

php - 使用PHP更新MYSQL数据库

php - 每秒记录 JSON 数据的最有效方法是什么

javascript - 通过子数组的聚合和排序来展平多维数组

javascript - 是否可以使用 JavaScript 中的 Set 来搜索一系列值?

python - 递归地颠倒链表中数字的顺序