作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一张 table
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
最佳答案
假设 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对于这样的工作。
关于php - 如何将平面数组排序为多维树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7874849/
我是一名优秀的程序员,十分优秀!