如何将平面数组排序为多维树
Posted
技术标签:
【中文标题】如何将平面数组排序为多维树【英文标题】:How to sort flat array into multidimensional tree 【发布时间】:2011-12-14 01:28:58 【问题描述】:我有一张这样的桌子
id catagory suboff
1 software 0
2 programming 1
3 Testing 1
4 Designing 1
5 Hospital 0
6 Doctor 5
7 Nurses 5
9 Teaching 0
10 php programming 2
11 .net programming 2
如何编写代码,根据suboff在多维数组中获取所有这些信息,如下,
-software
--programming
---php programming
--- .net programming
--testing
--designing
-hospital
--doctor
--nurses
-teaching
【问题讨论】:
什么意思?数据从何而来?数据库或文件或硬编码? PHP Reorder array to reflect parent / id hierarchy 或 Convert flat array to the multi-dimentional 和 many more 的可能重复项 【参考方案1】:假设 mysql 作为您的数据库引擎:
// We'll need two arrays for this
$temp = $result = array();
// Get the data from the DB
$table = mysql_query("SELECT * FROM table");
// Put it into one dimensional array with the row id as the index
while ($row = mysql_fetch_assoc($table))
$temp[$row['id']] = $row;
// Loop the 1D array and create the multi-dimensional array
for ($i = 1; isset($temp[$i]); $i++)
if ($temp[$i]['suboff'] > 0)
// This row has a parent
if (isset($temp[$temp[$i]['suboff']]))
// The parent row exists, add this row to the 'children' key of the parent
$temp[$temp[$i]['suboff']]['children'][] =& $temp[$i];
else
// The parent row doesn't exist - handle that case here
// For the purposes of this example, we'll treat it as a root node
$result[] =& $temp[$i];
else
// This row is a root node
$result[] =& $temp[$i];
// unset the 1D array
unset($temp);
// Here is the result
print_r($result);
使用references 完成这样的工作。
【讨论】:
【参考方案2】:恕我直言,逻辑是:
-
获取所有根元素(软件、医院等)
Foreach 根取子元素(用于您将进行编程、测试和设计的软件)
将子元素添加为子数组
在刚刚添加的子数组上递归循环
【讨论】:
【参考方案3】:您需要将整个表读入内存并将其变成一棵树,其中每个节点都可以通过其对应的 ID 号来标识。然后对树进行预先遍历以将其打印出来。
【讨论】:
【参考方案4】:演示:http://ideone.com/vk4po
$array = array(
array('1','software','0'),
array('2','programming','1'),
array('3','Testing','1'),
array('4','Designing','1'),
array('5','Hospital','0'),
array('6','Doctor','5'),
array('7','Nurses','5'),
array('9','Teaching','0'),
array('10','php programming','2'),
array('11','.net programming','2')
);
function menu_sort($results, $master = 0)
$open = array();
$return = NULL;
foreach($results as $result)
if($result[2] == $master)
if(!$open)
$return .= '<ul>';
$open = true;
$return .= '<li>'.$result[1];
$return .= menu_sort($results, $result[0]);
$return .= '</li>';
if($open)
$return .= '</ul>';
return $return;
echo menu_sort($array);
结果...
software programming php programming .net programming Testing Designing Hospital Doctor Nurses Teaching
【讨论】:
他要的是数组,而不是<ul />
。【参考方案5】:
在 PHP 中,我从数据库中获取数据:
"SELECT* FROM Table WHERE suboff LIKE 0"
foreach(item..)
"SELECT* FROM Table WHERE suboff LIKE item.ID"
foreach(item2..)
$result[item][item2]
【讨论】:
这非常低效,因为您必须进行大量查询。最好查询一次数据,让php在内存中进行提升(见我的回答)。 好的.. 我在上面使用了这个菜单,没有太多数据。但是你的权利我的解决方案不是很好的可扩展性。【参考方案6】:我会这样做的方式:
首先你需要解析这个表。我假设你可以自己做;如果没有,谷歌“正则表达式”,他们是你的朋友。
您使用的数据结构是经典的tree。您将需要两个数组来使用它。首先是节点数组$nodes
,其中键是节点 ID,值是节点名称,$links
,其中每个键是父节点,每个值是子节点数组($links[$id][] = $suboff
元素就足够了)。
现在你必须递归地下降你拥有的树。你引入一个带有这样签名的函数:
function print_node( $nodeID, $level = 1 )
这个函数应该使用 $level 填充破折号打印节点本身(存储在 $nodes 中的信息),并调用自身来渲染所有子节点。他们将依次渲染所有子节点等。您只需为***节点调用此函数即可。
【讨论】:
我猜他说的是数据库表。【参考方案7】:这是一种不同的方法,应该很容易理解。它要求您将表格按suboff
排序,即
SELECT * FROM table ORDER BY suboff
假设结果存储在$table
,你可以使用这个非常简洁的php代码:
// this will hold the result
$tree = array();
// used to find an entry using its id
$lookup = array();
foreach($table as $row)
if($row['suboff'] === 0)
// this has no parent, add it at base level
$tree[$row['category']] = array();
// store a reference
$lookup[$row['id']] =& $tree[$row['category']];
else
// find the right parent, add the category
$lookup[$row['suboff']][$row['category']] = array();
// store a reference
$lookup[$row['id']] =& $lookup[$row['suboff']][$row['category']];
【讨论】:
【参考方案8】:该类将平面类别数组转换为结构化树数组:
<?php
/**
* Creates a structured tree out of a flat category list
*/
class CategoryTree
/**
*
* @var array
*/
protected $categories = array();
/**
*
* @var array
*/
protected $tree = array();
/**
* Default constructor
* @param array $categories
*/
function __construct(array $categories)
$this->categories = $categories;
/**
* Process a subtree
* @param array $categories
* @param integer $parentId
* @return array
*/
protected function getSubtree(array $categories, $parentId = 0)
$tree = array();
foreach($categories as $category)
if($category['suboff'] == $parentId)
$tree[$category['id']] = $category;
$tree[$category['id']]['children'] = $this->getSubtree($categories, $category['id']);
return $tree;
/**
* Get the category tree as structured array
* @return array
*/
public function getTree()
if(empty($this->tree))
$this->tree = $this->getSubtree($this->categories, 0);
return $this->tree;
/**
* Get the category tree as string representation
* @return string
*/
public function __toString()
return "<pre>" . print_r($this->getTree(), true) . "</pre>";
// Now, use the class with the givven data:
$categories = array(
array(
'id' => 1,
'category' => 'software',
'suboff' => 0
),
array(
'id' => 2,
'category' => 'programming',
'suboff' => 1
),
array(
'id' => 3,
'category' => 'Testing',
'suboff' => 1
),
array(
'id' => 4,
'category' => 'Designing',
'suboff' => 1
),
array(
'id' => 5,
'category' => 'Hospital',
'suboff' => 0
),
array(
'id' => 6,
'category' => 'Doctor',
'suboff' => 5
),
array(
'id' => 7,
'category' => 'Nurses',
'suboff' => 5
),
array(
'id' => 9,
'category' => 'Teaching',
'suboff' => 0
),
array(
'id' => 10,
'category' => 'php programming',
'suboff' => 2
),
array(
'id' => 11,
'category' => '.net programming',
'suboff' => 2
)
);
$myTree = new CategoryTree($categories);
echo $myTree;
?>
【讨论】:
【参考方案9】:这个解决方案对我来说很好。
$array = array(
array('1','software','0'),
array('2','programming','1'),
array('3','Testing','1'),
array('4','Designing','1'),
array('5','Hospital','0'),
array('6','Doctor','5'),
array('7','Nurses','5'),
array('9','Teaching','0'),
array('10','php programming','2'),
array('11','.net programming','2')
);
$newArray = getTree($array);
function getTree( $rows, $suboff = 0)
$return = array();
foreach($rows as $row)
if($row[2] == $suboff)
$newrow = $row;
$subs = $this->getTree($rows, $row[0]);
if ( !empty($subs) )
$newrow['subs'] = $subs;
$return[] = $newrow;
return $return;
【讨论】:
【参考方案10】:这是我刚刚为我的应用写的,它就像一个魅力:)
$array = [
'i' => ['key' => 'i', 'name' => 'php programming', 'parent' => 'b'],
'g' => ['key' => 'g', 'name' => 'Nurses', 'parent' => 'e'],
'j' => ['key' => 'j', 'name' => '.net programming', 'parent' => 'b'],
'b' => ['key' => 'b', 'name' => 'programming', 'parent' => 'a'],
'a' => ['key' => 'a', 'name' => 'software', 'parent' => 'asd'],
'c' => ['key' => 'c', 'name' => 'Testing', 'parent' => 'a'],
'd' => ['key' => 'd', 'name' => 'Designing', 'parent' => 'a'],
'e' => ['key' => 'e', 'name' => 'Hospital', 'parent' => 'asd'],
'f' => ['key' => 'f', 'name' => 'Doctor', 'parent' => 'e'],
'h' => ['key' => 'h', 'name' => 'Teaching'],
];
function getAsTree(array &$array)
foreach ($array as $key => $item)
if (isset($item['parent']) && isset($array[$item['parent']]))
$array[$item['parent']]['children'][] = $item;
unset($array[$key]);
return getAsTree($array);
return $array;
结果如下:
--- a: software ------ b: programming --------- i: php programming --------- j: .net programming ------ c: Testing ------ d: Designing --- e: Hospital ------ g: Nurses ------ f: Doctor --- h: Teaching
【讨论】:
以上是关于如何将平面数组排序为多维树的主要内容,如果未能解决你的问题,请参考以下文章
array_uintersect 将多维数组的每一行中的特定元素与字符串的平面数组进行比较